\chapter{Networking}

% Label
\label{pgfId-10505}

% Label
\label{32252}

\begin{itemize}

\item{Exploring the Client Side}

\item{Services: The Internet Story}

\item{Java Networking: Socket and InetAddress}

\item{A Kind and Gentle Introduction to the Server Side}

\item{Simple Messaging Architecture}

\item{Chapter Wrap-Up}

\item{Exercises}

\end{itemize}

% Label
\label{pgfId-13176}
Networking is the story of Java. After all, Java, in its infancy, was an Internet programming language. Although this book has been entirely about threads and the potential of Java as a parallel language, we could not leave you without saying a few words (or chapters) about the potential of Java threads in the context of networked and distributed applications. In this chapter, we provide a self-contained introduction to networking. This introduction will provide (we hope) a solid basis for the next chapter, which introduces the ideas of distributed coordination (an area where both authors have invested a significant number of years of time doing research and applications).
\par

% Label
\label{pgfId-13177}
The discussion of this chapter is organized as follows. First, we introduce network programming from the client side. Here we adopt somewhat of an immersive approach (an approach often used by hackers) by first learning a bit about Internet-style services and interacting with them using widely available utilities such as telnet. Then, we present the Java API for programming the client side, followed by a discussion of the server side and its respective API. The chapter concludes with a general (and simple) class library for building client-server-socket applications, called Simple Messaging Architecture. We also show the potential for making use of material presented earlier (the
\texttt{RunQueue}
class) to minimize the overhead of thread creation on the server side.
\par

\section{Exploring the Client Side}

% Label
\label{pgfId-8895}

% Label
\label{64779}

% Label
\label{pgfId-8905}
In addition to powerful I/O abstractions, Java provides extensive support for networked computing. Of particular interest in the context of this book is the support for TCP/IP networking. It is beyond the scope of this particular textbook to define every aspect of networking here; however, there are a number of basics:
\par

\begin{itemize}

\item{TCP/IP, the transmission control protocol/Internet protocol, is really two protocols: TCP and IP. TCP roughly corresponds to the transport layer of the OSI protocol, which is an open international standard developed by the International Standards Organization (ISO) and consists of seven layers (two of which are named transport and network).}

% Label
\label{pgfId-8907}

\item{The practical significance of TCP is that it provides a virtual circuit service, which for all practical purposes can be thought of as a connection-oriented service, wherein you can be assured of having end-to-end continuity in a “conversation” without fear of losing the connection, subject to your link not being completely shutdown, of course.}

% Label
\label{pgfId-8908}

\item{The practical significance of IP is that it provides unique addresses for each device connected on the network. Each address is of the form A.B.C.D, where A, B, C, and D are called octets . The term octet refers to an 8-bit value. Thus, an IP address in its current form is actually a 32-bit value. IP addresses will eventually have at least 6 octets, which is being proposed as part of the IPv6 standards effort.}

% Label
\label{pgfId-8909}

\item{To support end-to-end connectivity, routing tables must exist to enable messages to be forwarded from one end of the “connection” to another. This is the real magic behind how the Internet is able to work.}

% Label
\label{pgfId-8910}

\end{itemize}

% Label
\label{pgfId-8911}
There is a great deal more to TCP/IP than can be covered in this book. One particularly great book on the subject is by W. Richard Stevens, whose book on Unix network programming is considered (and revered) as a classic, even outside of the Unix community.
\par

% Label
\label{pgfId-8918}
For the remainder of this chapter, we will take an
\emph{immersive}
approach to learning TCP/IP networking. For you to achieve the maximum benefits from this chapter, we recommend that you acquire access to a machine running Unix, which can be done quite inexpensively these days, since you can obtain the Linux operating system (as well as other versions of Unix) for free.
\ref{#id(pgfId-14359)}[MISSING HREF]

\par

% Label
\label{pgfId-8921}

\ref{id(90713)}[MISSING HREF]
shows the contents of the file /etc/services found on Unix. The /etc/services file is used precisely for what its name says: to indicate what services are running on what ports. Each line in the services file contains the following information:
\par

% Label
\label{pgfId-8926}

\textbf{service name port number/protocol}

\par

% Label
\label{pgfId-8947}
It is not essential to understand all details of this file, and what you see on your system will more than likely contain much more than shown in our example. The service name is a user-friendly name for the network service. For example,
\par

\begin{itemize}

\item{daytime is a widely familiar service to Unix users. It can be used to find the current date and time. The rdate command can be used to query the daytime service from any machine. This service can always be found on port 13. The service can be contacted by using the TCP protocol or the unreliable datagram protocol (UDP) . UDP will not be used in this book in detail. It is a protocol that can be used when you know that the underlying network is reasonably reliable (usually true on a LAN), and it has lower overhead than the TCP protocol.}

% Label
\label{pgfId-8950}

\item{telnet is a widely familar service as well. It is used to open a remote terminal session to another host. Nowadays, it is used less frequently, due to security considerations; ssh has taken its place to support encrypted remote sessions. Telnet service is always found on port 23, although it is now usually disabled or severly restricted on most systems.}

% Label
\label{pgfId-8951}

	%\begin{tabular}
	
	\begin{verbatim}
	

Telnet is also the name of a command that is found on Unix, and even on the Windows platform. Telnet (the command) is not restricted to connections with the telnet service. You can use telnet to connect to virtually any network service, assuming that service communicates with a plaintext protocol. We will show this in a later example.
	\end{verbatim}
	
	%\end{tabular}
	
\end{itemize}
/etc/services: the Unix collection of standard TCP/IP services
% Label
\label{pgfId-6800}
\# /etc/services:
% Label
\label{pgfId-6814}

% Label
\label{pgfId-8948}
\# Each line has
% Label
\label{pgfId-8949}
\# service name port/protocol
% Label
\label{pgfId-6815}
tcpmux 1/tcp
% Label
\label{pgfId-6816}
echo 7/tcp
% Label
\label{pgfId-6817}
echo 7/udp
% Label
\label{pgfId-6818}
discard 9/tcp
% Label
\label{pgfId-6819}
discard 9/udp
% Label
\label{pgfId-6820}
systat 11/tcp
% Label
\label{pgfId-6821}
daytime 13/tcp
% Label
\label{pgfId-6822}
daytime 13/udp
% Label
\label{pgfId-6823}
netstat 15/tcp
% Label
\label{pgfId-6824}
qotd 17/tcp
% Label
\label{pgfId-6825}
msp 18/tcp
% Label
\label{pgfId-6826}
msp 18/udp
% Label
\label{pgfId-6827}
chargen 19/tcp
% Label
\label{pgfId-6828}
chargen 19/udp
% Label
\label{pgfId-6830}
ftp 21/tcp
% Label
\label{pgfId-6831}
fsp 21/udp
% Label
\label{pgfId-6832}
ssh 22/tcp
% Label
\label{pgfId-6833}
ssh 22/udp
% Label
\label{pgfId-6834}
telnet 23/tcp
% Label
\label{pgfId-6836}
smtp 25/tcp
% Label
\label{pgfId-6838}
time 37/tcp
% Label
\label{pgfId-6839}
time 37/udp
% Label
\label{pgfId-7116}
\#
% Label
\label{pgfId-8936}
\# This file contains many more lines. Consult the /etc/services
% Label
\label{pgfId-8937}
\# file on your system to see ALL of what is available.
% Label
\label{pgfId-8935}

% Label
\label{pgfId-13187}
linuxconf 98/tcp
\section{Services: The Internet Story}

% Label
\label{pgfId-13188}

% Label
\label{48737}

% Label
\label{pgfId-13189}
Before we proceed to the next programming example, it is a worthwhile detour to see how these network services work. The knowledge gained by doing this will be used in the two subsequent examples, so this is not exactly an
\emph{aimless}
detour.
\par

% Label
\label{pgfId-8976}
The telnet command found in both the Unix and Windows operating systems allows you to specify the following:
\par

\begin{itemize}

\item{host: The machine to which you wish to connect.}

% Label
\label{pgfId-8977}

\item{service: The name of the service or port to which you wish to connect.}

% Label
\label{pgfId-8978}

\end{itemize}

% Label
\label{pgfId-8982}
By default, the telnet program will connect to the telnet service (port 23), if you elect not to specify an alternative service.
\par

% Label
\label{pgfId-8984}
Normally, when you use telnet to connect to a given host (here we will assume that the destination is Unix, which has a bona fide
\emph{remote-shell}
concept, unlike Windows), you are presented with a login. You log into an account, and then you can begin executing commands on the remote computer. See the box entitled “
\ref{id(48258)}[MISSING HREF]
” for an example of how a user would conduct a typical telnet session.
\par

	%\begin{tabular}
	
	\begin{verbatim}
	


A Typical Telnet Session
	\end{verbatim}
	
	\begin{verbatim}
	

[gkt@gauss gkt]$ telnet euler
	\end{verbatim}
	
	\begin{verbatim}
	

Trying 140.192.38.154...
	\end{verbatim}
	
	\begin{verbatim}
	

Connected to euler.jhpc.cs.depaul.edu.
	\end{verbatim}
	
	\begin{verbatim}
	

Escape character is ‘^]’.
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

SunOS 5.7
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

login: gkt
	\end{verbatim}
	
	\begin{verbatim}
	

Password:
	\end{verbatim}
	
	\begin{verbatim}
	

Last login: Wed Dec 22 03:44:29 from gauss
	\end{verbatim}
	
	\begin{verbatim}
	

bash-2.03$ ls
	\end{verbatim}
	
	\begin{verbatim}
	

2q                             Jthreads.zip
	\end{verbatim}
	
	\begin{verbatim}
	

372                            JThreadsNew.zip
	\end{verbatim}
	
	\begin{verbatim}
	

420                            kaffe-1.0.5
	\end{verbatim}
	
	\begin{verbatim}
	

apt                            kaffe-1.0.5.zip
	\end{verbatim}
	
	\begin{verbatim}
	

axhome                         keep
	\end{verbatim}
	
	\begin{verbatim}
	

beta                           letter
	\end{verbatim}
	
	\begin{verbatim}
	

bootnet.img                    loyola
	\end{verbatim}
	
	\begin{verbatim}
	

checkins                       luiz
	\end{verbatim}
	
	\begin{verbatim}
	

christophe                     lyon
	\end{verbatim}
	
	\begin{verbatim}
	

controlpanel                   lyon2
	\end{verbatim}
	
	\begin{verbatim}
	

core                           mail
	\end{verbatim}
	
	\begin{verbatim}
	

data                           manuals.tar.gz
	\end{verbatim}
	
	\begin{verbatim}
	

Desktop                        ncftp-3.0beta21
	\end{verbatim}
	
	\begin{verbatim}
	

JThreads.tar.gz
	\end{verbatim}
	
	\begin{verbatim}
	

bash-2.03$ exit            
	\end{verbatim}
	
	\begin{verbatim}
	

logout
	\end{verbatim}
	
	\begin{verbatim}
	

Connection closed by foreign host.
	\end{verbatim}
	
	\begin{verbatim}
	

[gkt@gauss gkt]$
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	%\end{tabular}
	
% Label
\label{pgfId-9082}
In this example, a telnet session is opened from an existing shell running on Unix (the same can be done in Windows) using the
\textbf{telnet}
client program and passing the name of a host (euler) as the first command-line argument. When connecting to a remote telnet service, a terminal session is opened, and a
\textbf{login}
program is executed. The login program exists to accept your username and password and then to subsequently authenticate you. When authenticated (which on Unix is achieved by using the password crypt utility to compare the encrypted password supplied with the encrypted password usually found in /etc/passwd or /etc/shadow), the login program (currently running as the superuser) switches user to the authenticated user (gkt) and executes a shell
\emph{as that user}
. Bear in mind that this entire process is being carried out under the auspices of the telnet service. (
\textbf{telnetd}
or
\textbf{in.telnetd}
is the name of the program executable under Unix.) The input and output are both “connected” to the terminal itself.
\par

% Label
\label{pgfId-9084}
How exactly is this possible?
\par

% Label
\label{pgfId-9088}
The answer is a bit involved, and we will only provide an executive summary here. The telnet connection is made possible via a TCP/IP connection called a
\emph{socket}
. When a socket is created, file descriptors are available to read from and to write to the socket. When connecting via telnet to any Unix system, a socket exists at all times between the client (your telnet program) and the server (the telnet daemon). Any input you type in the telnet client session is actually sent via the output file descriptor associated with this socket. Similarly, any output generated by a remotely running program is actually taken as input by the telnet client program. There is one interesting detail: typing a character on your keyboard is not a one-way operation. Why? It has to do with the way the telnet client itself works. Telnet never displays anything that is not written explicitly to the standard output or standard error (remotely). Furthermore, the telnet service is in many respects a broker. Most of the time, the telnet service executes a shell on the user’s behalf. Any input that goes to the telnet service after the shell has been created remotely is in fact going straight to the shell. It is beyond the scope of this book to cover the details of the Unix shell (many good books already exist on this topic); however, the (remotely running) shell itself takes full responsibility for handling this input. As characters are received by the shell, they are echoed. This “echoing” of characters is output, which is written to the socket connecting the telnet client and the telnet service.
\par

% Label
\label{pgfId-9096}
Thus, whenever a character is typed in a telnet session, there is no guarantee that it will be echoed on the screen. It is only echoed from the server at will. At first, this entire process appears to be somewhat unnecessary and, certainly, not terribly efficient; however, closer examination reveals that it is a necessary evil of designing a remote terminal. You simply do not want everything to be echoed. The login program, which is actually a special form of a remote shell needs the ability to suppress echoing of the password. If the telnet client program were to do this echoing in advance, it would effectively deny the server side the opportunity to suppress echoing. It is for this reason alone (among others) that the telnet client is kept ultra-generic in nature. It’s only mission in life is to send characters and receive characters. It literally does nothing else.
\par

% Label
\label{pgfId-9101}
That said, many telnet clients do much more than this. The Windows telnet clients perform terminal emulation. This allows the client to have a little more intelligence and ensure that certain character sequences (known as escape sequences) are interpreted and displayed properly. It is important to note, however, that this is primarily for the convenience of the user and is not in any way connected to the telnet protocol itself.
\par

\subsubsection{Destination Sendmail}

% Label
\label{pgfId-9125}

% Label
\label{pgfId-9384}
The detour to telnet exposed one reality about the telnet client found on your computer. It can be used to connect, literally, to anything. And this is where the fun of network hacking begins. Please note that hacking by our definition does not mean breaking the law. We humbly request that you observe the security note on the following page.
\par

	%\begin{tabular}
	
% Label
\label{pgfId-9387}
Security Note
	\begin{verbatim}
	

The examples shown here can get you into trouble. Before accessing any computer on your (or another) network, it is your responsbility to ensure that you have permission to do so. We (Prentice Hall and the authors) cannot assume any responsibility for illegal behavior resulting from the misuse of the information provided in this chapter.
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	%\end{tabular}
	
% Label
\label{pgfId-9404}
Now back to the fun. The
\ref{id(38933)}[MISSING HREF]
shows an example of a telnet session with another network service called SMTP, the Simple Mail Transport Protocol, which is a major protocol used on the Internet to send mail messages. Is is also known commonly as sendmail, or the
\emph{mail agent}
. The SMTP protocol consists of a number of messages. You can learn more about this protocol by reading the so-called RFC documents (request for comments), which represent proposals to the Internet Engineering Task Force (IETF) that are intended to become, to expand, or to clarify open standards specifically related to the Internet.
\par

% Label
\label{pgfId-9657}
As mentioned, the approach to this chapter is intended to be immersive. The session shown in the
\ref{id(38933)}[MISSING HREF]
makes use of a telnet client to access the sendmail service (on Unix), which is a widely used implementation of the SMTP protocol, especially on Unix machines (Solaris and Linux). The Microsoft Exchange Server product supports the SMTP protocol, as well, and it should be possible for you to adapt what you see here to see what is done by Microsoft’s implementation of SMTP.
\par

	%\begin{tabular}
	
% Label
\label{pgfId-9661}

% Label
\label{38933}
Using Telnet to Contact sendmail: The Unix Mail Delivery Service
	\begin{verbatim}
	

[gkt@gauss gkt]$ 
telnet leibniz smtp

	\end{verbatim}
	
	\begin{verbatim}
	

Trying 140.192.38.152...
	\end{verbatim}
	
	\begin{verbatim}
	

Connected to leibniz.jhpc.cs.depaul.edu.
	\end{verbatim}
	
	\begin{verbatim}
	

Escape character is ‘^]’.
	\end{verbatim}
	
	\begin{verbatim}
	

220 leibniz.jhpc.cs.depaul.edu ESMTP Sendmail 8.9.3/8.9.3; Wed, 22 Dec 1999 17:59:36 -0600
	\end{verbatim}
	
	\begin{verbatim}
	


HELP

	\end{verbatim}
	
	\begin{verbatim}
	

214-This is Sendmail version 8.9.3
	\end{verbatim}
	
	\begin{verbatim}
	

214-Topics:
	\end{verbatim}
	
	\begin{verbatim}
	

214-    HELO    EHLO    MAIL    RCPT    DATA
	\end{verbatim}
	
	\begin{verbatim}
	

214-    RSET    NOOP    QUIT    HELP    VRFY
	\end{verbatim}
	
	\begin{verbatim}
	

214-    EXPN    VERB    ETRN    DSN
	\end{verbatim}
	
	\begin{verbatim}
	

214-For more info use “HELP <topic>”.
	\end{verbatim}
	
	\begin{verbatim}
	

214-To report bugs in the implementation send email to
	\end{verbatim}
	
	\begin{verbatim}
	

214-    sendmail-bugs@sendmail.org.
	\end{verbatim}
	
	\begin{verbatim}
	

214-For local information send email to Postmaster at your site.
	\end{verbatim}
	
	\begin{verbatim}
	

214 End of HELP info
	\end{verbatim}
	
	\begin{verbatim}
	


HELP EHLO

	\end{verbatim}
	
	\begin{verbatim}
	

214-EHLO <hostname>
	\end{verbatim}
	
	\begin{verbatim}
	

214-    Introduce yourself, and request extended SMTP mode.
	\end{verbatim}
	
	\begin{verbatim}
	

214-Possible replies include:
	\end{verbatim}
	
	\begin{verbatim}
	

// You should run ‘telnet’ to see the list of possible replies.
	\end{verbatim}
	
	\begin{verbatim}
	

214 End of HELP info
	\end{verbatim}
	
	\begin{verbatim}
	


EHLO gauss.jhpc.cs.depaul.edu

	\end{verbatim}
	
	\begin{verbatim}
	

250-leibniz.jhpc.cs.depaul.edu Hello IDENT:gkt@gauss [140.192.38.153], pleased to meet you
	\end{verbatim}
	
	\begin{verbatim}
	

250-EXPN
	\end{verbatim}
	
	\begin{verbatim}
	

// Again this has been abbreviated.
	\end{verbatim}
	
	\begin{verbatim}
	

250 HELP
	\end{verbatim}
	
	\begin{verbatim}
	


MAIL FROM: gkt@cs.depaul.edu
                                            
	\end{verbatim}
	
	\begin{verbatim}
	

250 gkt@cs.depaul.edu... Sender ok
	\end{verbatim}
	
	\begin{verbatim}
	


RCPT TO: pshafae@leibniz.jhpc.cs.depaul.edu

	\end{verbatim}
	
	\begin{verbatim}
	

250 pshafae@leibniz.jhpc.cs.depaul.edu... Recipient ok
	\end{verbatim}
	
	\begin{verbatim}
	


DATA

	\end{verbatim}
	
	\begin{verbatim}
	

354 Enter mail, end with “.” on a line by itself
	\end{verbatim}
	
	\begin{verbatim}
	


Hi John,

	\end{verbatim}
	
	\begin{verbatim}
	


It seems like you are the only person I can send e-mail to in my list.

	\end{verbatim}
	
	\begin{verbatim}
	


George

	\end{verbatim}
	
	\begin{verbatim}
	


.

	\end{verbatim}
	
	\begin{verbatim}
	

250 SAA07772 Message accepted for delivery
	\end{verbatim}
	
	\begin{verbatim}
	


QUIT

	\end{verbatim}
	
	\begin{verbatim}
	

221 leibniz.jhpc.cs.depaul.edu closing connection
	\end{verbatim}
	
	\begin{verbatim}
	

Connection closed by foreign host.
	\end{verbatim}
	
	%\end{tabular}
	
% Label
\label{pgfId-9462}
Let us now examine the session in greater detail. The first item of note occurs before the telnet session is even established:
\par

	\begin{verbatim}
	

	telnet leibniz smtp
	\end{verbatim}
	
% Label
\label{pgfId-9465}
A connection is to be opened to the
\emph{smtp}
service running on host
\emph{leibniz}
. Some versions of telnet may require you to specify the port where the smtp service is running (25) instead of smtp. As we discussed earlier, telnet may connect to any desired port.
\par

% Label
\label{pgfId-9466}
The sendmail service represents an interactive protocol. This means that it has been designed to be used interactively, say, from a terminal operated by a human (like you!) The HELP comand is the most useful command available in sendmail. When typed, a great deal of useful information is dumped to your terminal, including the version of sendmail that is running, the topics that are available, and much needed information on how to report bugs in the implementation. We will not show how to use all of the commands here, but limit our discussion to how to use this interactive session to compose a simple plaintext message using the various commands that will ultimately be sent to a given recipient.
\par

% Label
\label{pgfId-9475}
To send a message, the following commands must be sent:
\par

	\begin{verbatim}
	

EHLO hostname
	\end{verbatim}
	
% Label
\label{pgfId-9485}
The EHLO command is used to introduce yourself (by specifying the originating domain name of the message) and to enable extended SMTP commands. This is the command used by modern mail clients, such as Netscape and Internet Explorer, which both need all of the features of the SMTP protocol in order to compose messages. The MAIL command is used to specify the originator (sender) of the e-mail message:
\par

	\begin{verbatim}
	

	MAIL FROM: sender’s e-mail address
	\end{verbatim}
	
% Label
\label{pgfId-9486}
This information is normally obtained (easily) from the mail client, which has total knowledge of who the sender is by inspecting the user profile (in the case of a browser-based e-mail program) or from the user-id/host-id combination, in the case of the old Unix command-line mail utilities. The RCPT command is used to specify the recipient of the e-mail message:
\par

	\begin{verbatim}
	

	RCPT TO: recipient’s e-mail address
	\end{verbatim}
	
% Label
\label{pgfId-9487}
There is usually some attempt made to check this address for well-formedness. This information is usualy passed on from the composition window from the mail client program. Only a single recipient is specified. We’ll talk about how multiple messages can be handled. The DATA command is used to indicate that the client is about to send the body (text) of the e-mail message:
\par

	\begin{verbatim}
	

	DATA
	\end{verbatim}
	
% Label
\label{pgfId-9488}
Once this command is issued, the message body must be sent in its entirety, followed by “.” as a single, self-contained line of text, terminated by a newline character. You can send any kind of document using the DATA command. We’ll not discuss that here in any kind of detail; however, another Internet standard, called MIME, allows you to take any kind of data and structure it in such a way that it can be encoded in a plaintext format for transfer via SMTP. The QUIT command is the polite way of bidding adieux to sendmail:
\par

	\begin{verbatim}
	

	QUIT
	\end{verbatim}
	
% Label
\label{pgfId-9481}
Strictly speaking, it is not essential for delivering the message. Once the DATA command has terminated, the message is formally accepted for delivery.
\par

% Label
\label{pgfId-9710}
This session forms the basis of our first network programming example. We will return to this example shortly. First, we need to clear some preliminaries out of the way. Then, we will present a complete implementation of an SMTP client. If you absolutely cannot wait, please feel free to examine the source code for class
\texttt{SendMail}
, which is presented in
\ref{id(13292)}[MISSING HREF]
.
\par

\section{Java Networking: Socket and InetAddress}

% Label
\label{pgfId-9715}

% Label
\label{11958}

% Label
\label{pgfId-9724}
Java as a language is among the elite when it comes to support for networking and I/O. Those familiar with the sockets programming interfaces for the C language in Unix and Windows NT libraries are almost certain to find the Java solution to be much easier to use and comprehend. We will not discuss the C programming interfaces here. We will, however, make the observation that neither author terribly misses the complexity of the lower level interfaces all that much, and we believe that you will feel the same way after having explored Java’s networking in greater detail beyond what is covered here.
\par

% Label
\label{pgfId-9725}
As the strategy of this chapter is intended to be immersive, we will present the Java classes that are needed to address a particular example (only as needed) with the idea of gradually unveiling all of the Java networking classes by the end of the chapter.
\par

% Label
\label{pgfId-9730}
The first set of classes we present are those needed from the client-side perspective. Consider the foregoing discussion on SMTP. This discussion centered entirely on the client. The client does the following:
\par

\begin{itemize}

\item{connects to the server}

% Label
\label{pgfId-9735}

\item{sends commands to the server}

% Label
\label{pgfId-9736}

\item{receives responses from the server}

% Label
\label{pgfId-9743}

\item{closes the connection to the server}

% Label
\label{pgfId-9738}

\end{itemize}

% Label
\label{pgfId-9739}
Let us now consider how Java supports each of these aspects, again with the focus being only on the client side. To connect to SMTP, we first need to consider exactly to what we are establishing a connection: a TCP/IP service. To connect to a TCP/IP service, a standard mechanism called a
\emph{socket}
exists. The concept of a socket is widely familar. We use sockets to plug in our electrical appliances, almost on a daily basis.
\par

% Label
\label{pgfId-9772}
The Java
\texttt{Socket}
class is used by clients to create a connection to a TCP/IP service. It is used in
\ref{id(13292)}[MISSING HREF]
. (The code is a bit involved, because it makes use of the Abstract Windowing Toolkit, and we will discuss the essentials for those who are unfamiliar with it in just a bit.) A socket is created in the
\texttt{sendMail()}
method with the following statement:
\par

	\begin{verbatim}
	

     smtpConnection = new Socket(smtpHost.getText(),25);
	\end{verbatim}
	
% Label
\label{pgfId-9779}
The
\texttt{Socket}
constructor requires a valid hostname or IP address to be specified along with a port, which indicates the service to which you want to connect. The service to which we are connecting is SMTP (used to send mail as discussed earlier), which is a standard Internet service for mail delivery that always runs on port 25. How did we know? Well, the answer is easy when you are working on the Unix platform. The /etc/services file (shown in
\ref{id(13292)}[MISSING HREF]
) indicates that the “smtp” service is a “tcp” service running on port 25:
\par

% Label
\label{pgfId-9776}
smtp 25/tcp
% Label
\label{pgfId-9794}
There are other interesting classes that prove useful from a client-side perspective that will be introduced shortly. Let us now consider how we complete the remaining steps to send commands to the server, receive responses from the server, and close the connection.
\par

% Label
\label{pgfId-9795}
These remaining steps all involve the use of I/O classes that we discussed in the first part of this chapter. Once a socket is created, a handle can be obtained to both the input and the output streams associated with the socket. Recall that a socket is a connection. To do anything useful with it, however, requires the capabilities only offered by Java’s I/O package.
\par

% Label
\label{pgfId-9797}
Again, let us focus only on the code in the
\texttt{sendMail()}
method in
\ref{id(13292)}[MISSING HREF]
. The following excerpt from the beginning of this method illustrates how you can capture the input and output streams:
\par

	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

	OutputStream os = smtpConnection.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

	OutputStreamWriter osw = new OutputStreamWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

	out = new PrintWriter(osw);
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

	InputStream is = smtpConnection.getInputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

	in = new InputStreamReader(is);
	\end{verbatim}
	
% Label
\label{pgfId-9833}
Only the two statements initialize
\texttt{os}
and
\texttt{is}
objects are actually needed.
\texttt{os}
is the object that can be used to write output to the server, while
\texttt{is}
is the object used to read input from the server. As noted earlier in the section on stream composition, one of the apparent nuisances of Java is the need to do layering in order to get the kind of stream you actually want. Thus, you need to think about what you actually want. In the case of SMTP, the commands being sent to the server are actually strings terminated by a newline character. Thus, we need a stream that supports a convenience method to facilitate writing entire lines (
\texttt{PrintWriter}
provides a
\texttt{println()}
method, which will do!) Unfortunately, to create a
\texttt{PrintWriter}
instance, we need a
\texttt{Writer}
instance as the underlying stream. An
\texttt{OutputStream}
reference can only be turned into a
\texttt{Writer}
by using the briding class, the class
\texttt{OutputStreamWriter}
. Ultimately, object
\texttt{out}
is initialized, which represents the object that will actually be used to send commands to the server.
\par

% Label
\label{pgfId-9834}
A similar task is performed to initialize variable
\texttt{in}
.
\par

% Label
\label{pgfId-9885}
The code in
\ref{id(13292)}[MISSING HREF]
is an implementation of a graphical client to sendmail. This code makes use of the Java framework for creating basic graphical user interfaces (GUI) known as the Abstract Windowing Toolkit (AWT). It is beyond the scope of this book to cover AWT in detail; however, we will present enough information so you can get the gist of what it does. AWT is covered in many excellent textbooks. We will now discuss the code, focusing on a few aspects:
\par

\begin{itemize}

\item{the use of Java packages}

% Label
\label{pgfId-9892}

\item{the use of OOP to create a GUI}

% Label
\label{pgfId-9896}

\item{the constructor}

% Label
\label{pgfId-9897}

\item{the use of a “layout” container}

% Label
\label{pgfId-9898}

\item{event handling}

% Label
\label{pgfId-9899}

\end{itemize}

% Label
\label{pgfId-9900}
Java packages used
% Label
\label{pgfId-9887}
This particular example makes use of a number of Java packages, each of which appears in an import declaration: java.awt, java.awt.event, java.io, java.net, and java.util. The java.awt package provides the classes for GUI containers (
\texttt{Frame}
is used in our example) and components (
\texttt{Button}
,
\texttt{Label}
,
\texttt{TextArea}
, and
\texttt{TextField}
are used in the example). The java.awt.event package provides classes for handling events generated by those containers and components. We only need an event handler for the
\texttt{Button}
object that, when pressed, is what causes mail to be sent. java.net and java.io are both used to provide support for sockets and streams. As mentioned earlier, streams are necessary in order to actually perform I/O on the socket. The socket itself provides no direct I/O capability.
\par

% Label
\label{pgfId-9904}
The use of OOP to create the GUI
% Label
\label{pgfId-9910}
When designing graphical interfaces in Java, it is almost never the case that you start entirely from scratch (unless you are on the development team at Sun!) Java classes can usually be extended to define a custom interface. We have chosen the
\texttt{Frame}
class, which you can think of as a Window that can support other fancy features, such as having a title or a menu bar or to support pop-up dialog boxes. Our approach here is thus to extend the
\texttt{Frame}
class and then to initialize the
\texttt{Frame}
object accordingly. This is done in the constructor. In addition to extending the
\texttt{Frame}
class, we implement an interface called the
\texttt{ActionListener}
. The “listener” pattern is an innovation of Java’s GUI framework, which allows an object that is interested in events generated by another object to
\emph{subscribe}
to the event. The subscription concept (in theory) allows a GUI implementation to be very efficient, since the scope of an event is bounded to a (usually) small number of objects. The actual subscription is done in the constructor, which is discussed in the next paragraph.
\par

% Label
\label{pgfId-9911}
The constructor
% Label
\label{pgfId-9928}
The constructor for this class looks a bit scary; however, most of what is going on is remarkably intuitive and self-documenting. In fact, most of what is happening here is true to the responsibility of a constructor: A representation is being constructed. The call to the superclass’s constructor, via the
\texttt{super()}
method, is used to set the frame’s title. A layout manager is established and will be discussed in more detail shortly. A number of
\texttt{Label}
and
\texttt{TextField}
instances are created. A label is a fairly simple component that is merely used to place text on the GUI. We use it here to label an adjacent
\texttt{TextField}
instance, which is used to accept a single line of input from the user.
\texttt{TextField}
instances are used to fetch the
\textbf{to}
,
\textbf{from}
,
\textbf{subject}
, and
\textbf{SMTP host}
values from the user. A
\texttt{TextArea}
instance is used to hold the message to be sent.
\texttt{TextField}
is in many respects a specialization of
\texttt{TextArea}
, since
\texttt{TextArea}
is able to accept multiple lines of input. The last component added to the frame is the “send” button. It is here where something occurs that may not be widely familiar to all readers:
\par

	\begin{verbatim}
	

		send = new Button(“Send”);
	\end{verbatim}
	
	\begin{verbatim}
	

		send.addActionListener(this);
	\end{verbatim}
	
% Label
\label{pgfId-9936}
The instance
\texttt{send}
is created. After it is created, the
\texttt{addActionListener()}
method is called, which enables the current object (
\texttt{this}
) to subscribe to events that may be generated by the
\texttt{send}
Button when it is pressed. The
\texttt{addActionListener()}
method has the following signature:
\par

	\begin{verbatim}
	

       public void addActionListener(ActionListener)
	\end{verbatim}
	
% Label
\label{pgfId-9940}
The class we have defined can double as an
\texttt{ActionListener}
, because it
\emph{implements}
the
\texttt{ActionListener}
interface. This one statement is an example of a contract being made between two objects (an instance of a
\texttt{SendMail}
,
\texttt{this}
, and an instance of a contained
\texttt{Button}
,
\texttt{send}
). In order for this contract to be completely fulfilled, however, the
\texttt{SendMail}
class must also provide a definition of the
\texttt{actionPerformed()}
method, which appears in the code, as is discussed shortly.
\par

% Label
\label{pgfId-9955}
Layouts
% Label
\label{pgfId-9970}
Most graphical-interface toolkits have some notion of how to place components (such as
\texttt{Label}
,
\texttt{TextField}
, and
\texttt{Button}
) within a container (such as a
\texttt{Frame}
). In Java, the layout concept is intentionally very abstract. This has much to do with Java’s origins, wherein Java was intended to be the quintessential Web programming language. The inception of the Web brought with it the notion that the display of the Web interface should be possible on a wide variety of devices. Java would only sell in the browser if it could adhere to this policy--at least that was the hope. Of course, industry politics ultimately led to a virtually Java-free browser world, despite all of the right technical decisions having been made. Java’s layout concept was the right technical decision. Using Java layouts, the programmer could describe the relative placement of components with respect to one another within a container without worrying about
\emph{exactly}
where the components would be placed. Although we have not gone through the pain and suffering to make the perfect-looking interface here, it is remarkable how (with little effort) you can create a reasonably attractive interface that is fully functional in a fairly small code footprint.
\par

% Label
\label{pgfId-9969}
Earlier, in the discussion of the constructor, we mentioned that more would be said shortly about layouts. Well, that was almost true. In any event, the constructor makes use of a layout object. This is done by calling the
\texttt{setLayout()}
method, which is inherited from the
\texttt{Frame}
class (and ultimately from the
\texttt{Container}
class). In the example, we use an instance of
\texttt{GridBagLayout}
to perform the actual layout. A
\texttt{GridBagLayout}
can be thought of (for practical purposes) as a partitioning of a space into a grid of variable cell sizes. The traditional notion of a grid is also supported in Java by the
\texttt{GridLayout}
class.
\texttt{GridBagLayout}
is sufficiently advanced. You don’t need to know much more about it and can continue to our discussion of the
\texttt{sendMail()}
method; however, for completeness, the details are presented in the remainder of this section.
\par

% Label
\label{pgfId-9973}
To use
\texttt{GridBagLayout}
, you do not have to indicate how many grid cells there will be. You simply have to define a constraints object for each component you wish to place in the container. We have taken the approach of laying out the components in row-major order. The
\texttt{GridBagConstraints}
class must be used to define how components are actually added. In our example, two instances of
\texttt{GridBagConstraints}
,
\texttt{gbc0}
and
\texttt{gbc}
, are used for this purpose.
\texttt{gbc0}
is used for the first object being placed on a row, and
\texttt{gbc}
is used for the very last object placed on a row. This scheme works perfectly well for our example and is primarily being used to support the case where we need to place an instance of a
\texttt{Label}
next to an instance of a
\texttt{TextField}
. You will need to study the
\texttt{GridBagConstraints}
class for more details. We only make use of the
\texttt{gridwidth}
field of this object, which is a public instance variable that allows us to specify the number of grid cells that are “occupied” by a component. In practice, there are two values used:
\par

\begin{itemize}

\item{1 : Use a single grid cell for the component.}

% Label
\label{pgfId-9982}

\item{GridBagConstraints.REMAINDER : Use however many cells are needed to fill the row. In practice, this often turns out to be one cell (the last component you are adding to the container). The practical consequence of using this value for the gridwidth is that it also causes the next component you add to be placed on the next row.}

% Label
\label{pgfId-9983}

\end{itemize}

% Label
\label{pgfId-9857}
Event handling
% Label
\label{pgfId-9985}
The event handler,
\texttt{actionPerformed(ActionEvent ae)}
, is called whenever the
\texttt{send}
button is pressed. When this method is called, the parameter
\texttt{ae}
contains information that can be used to determine more information about the event. In practice, you usually know exactly what the event
\emph{should}
be. This is particularly true in the case of our application, since the
\texttt{send}
object added the
\texttt{SendMail}
instance
\texttt{this}
as the only listener. Furthermore, there were no other objects that called
\texttt{addActionListener(this)}
at construction time. Nonetheless, the code here errs on the conservative side by checking that the source of the event is precisely the object that we are expecting. Since we saved a reference to the
\texttt{send}
button at construction time, the
\texttt{getSource()}
method can be called on the
\texttt{ae}
method to verify that the
\texttt{send}
object actually generated the event. The beauty of Java is that we can actually do reference comparison to check that the source of the event is the
\texttt{send}
button itself:
\par

	\begin{verbatim}
	

	if (ae.getSource() == send) ...
	\end{verbatim}
	
% Label
\label{pgfId-9984}
One might be tempted to rush to judgment and suggest that this test is completely unnecesary and should be eliminated. After all, there is only one object that can generate an
\texttt{ActionEvent}
(the
\texttt{send}
button instance). We would respond “guilty as charged” in this case. Now consider what would happen if you add another button
\texttt{cancel}
to change your mind. The current code would be easy to modify to accommodate the new button. Code that did not explicitly test for the
\texttt{send}
button would possibly require extensive modifications. In general, you should always keep references to components that generate events and explicitly test whether the source of a given event object matches the object that is responsible for having generated the event.
\par

% Label
\label{pgfId-9999}
Sending mail: the final frontier
% Label
\label{pgfId-9876}
In graphical applications, it is often the case that the GUI code is harder to explain than the actual business problem being solved. This will no doubt help to you appreciate your e-mail client, which undoubtedly has a significantly more involved interface than our
\texttt{SendMail}
program. When the
\texttt{send}
button is pressed, this is what triggers a call to the private
\texttt{sendMail()}
method, which actually uses all of the information captured by the GUI to send the mail.
\par

% Label
\label{pgfId-10001}
The
\texttt{sendMail()}
method itself is fairly straightforward. As shown earlier, the first several statements in this method are dedicated to opening a socket to the SMTP service. Then, the
\texttt{InputStream}
and
\texttt{OutputStream}
references are obtained and turned into appropriate
\texttt{Reader}
and
\texttt{Writer}
streams, respectively, to perform actual I/O on the connection. Now the session can actually begin. As shown earlier in
\ref{id(38933)}[MISSING HREF]
the rest of the code is dedicated to mimicking what happens during the interactive session. SMTP commands are sent, one at a time, to prepare a message for delivery. Each message being sent is packed into a character string (the
\texttt{command}
variable) and sent using the
\texttt{send()}
method. The
\texttt{receive()}
method is called to ensure the retrieval response from the server.
\par

% Label
\label{pgfId-10167}
The
\texttt{send()}
method uses the output stream object
\texttt{out}
to transmit the message to the SMTP service. Since the SMTP service works with line-oriented commands, we use the
\texttt{println()}
method provided by the
\texttt{PrintWriter}
class (the class of the
\texttt{out}
instance). Some care is required when working with a socket. Just because we actually sent characters via the output stream does not imply that the characters are actually bound for the network immediately. This is due to
\emph{buffering}
, which is used to improve I/O performance in virtually all programming languages and libraries for I/O. To ensure that the data are written to the underlying stream, Java provides the method
\texttt{flush()}
. When called, any characters that have been buffered will be forcibly written to the underlying stream. In general, you’ll need to do this to guarantee a response from a server, since you cannot know in general how many layers of streams actually exist. It could well be that there is no buffering in any of the layers in a particular situation; however, in this case, it still does no harm to call
\texttt{flush()}
. Java does whatever it can to keep the cost of a call to
\texttt{flush()}
to a minimum by caching information about whether the underlying stream is actually buffered.
\par

% Label
\label{pgfId-10184}
The
\texttt{receive()}
method is a bit more involved. To some extent, this has a great deal to do with the way that the SMTP protocol works. Whenever a message is sent to the server, it is possible that more than one line of output is returned to the client. Unfortunately, the protocol itself does not give you any way of finding out how much output will be returned. You can inspect this for yourself by visiting the box where we conducted the SMTP session using telnet. When sending the EHLO command, several lines of responses are generated. A more elaborate mail client would use all of these responses to know precisely what kind of mail can be sent using the service. (There are a good number of SMTP implementations out there, and not all of them adhere to the current standard.) Because our
\texttt{sendmail}
client is only designed to send ASCII text messages, we are more or less guaranteed to be able to send mail using any version (even old versions) of SMTP. The consequence of not knowing how much output can be generated is somewhat problematic. If the client keeps trying to read from the underlying stream, it will eventually block. This will prevent the client from writing the next command to the server, which is necessary in order to get more responses from the server. It is almost a Catch 22 situation, but can be solved in one of two ways:
\par

\begin{itemize}

\item{Test the stream in to determine whether a single character can be read from the stream without blocking. All classes inherited from the Reader class have the ability to determine this using the ready() method.}

% Label
\label{pgfId-10171}

\item{Read responses from the server in a separate thread.}

% Label
\label{pgfId-10172}

\end{itemize}

% Label
\label{pgfId-10188}
The code in the present example adopts the first approach. (The second approach has also been coded and is provided in the accompanying CD and on the Web.) The
\texttt{receive()}
method is designed under the assumption that it is called only after
\texttt{send()}
. Thus, it is guaranteed that there will be at least one character returned as a response without blocking indefinitely. The only reason that this would not happen is if the socket connection died, in which case an I/O exception would occur, which is acceptable. Characters are read in a bottom-tested loop that terminates only when the next attempt to read a character would cause the next
\texttt{read()}
to block indefinitely.
\par

% Label
\label{pgfId-10205}
Once the QUIT message has been sent and the response received, the mail message can be assumed to have been sent successfully. When the
\texttt{sendMail()}
method exits, you can assume that control returns to the
\texttt{actionPerformed()}
method, which destroys the
\texttt{SendMail}
GUI and exits with a normal (0) exit status code.
\par

	\begin{verbatim}
	


	\end{verbatim}
	SendMail.java
	\begin{verbatim}
	

package com.toolsofcomputing.networking;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

import java.awt.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.awt.event.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class SendMailSync extends Frame implements ActionListener {
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private TextField to, from, subject, smtpHost;
	\end{verbatim}
	
	\begin{verbatim}
	

    private TextArea message;
	\end{verbatim}
	
	\begin{verbatim}
	

    private Button send;
	\end{verbatim}
	
	\begin{verbatim}
	

    private Socket smtpConnection;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private PrintWriter out;
	\end{verbatim}
	
	\begin{verbatim}
	

    private InputStreamReader in;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public SendMailSync() {
	\end{verbatim}
	
	\begin{verbatim}
	

        super(“SendMail by Tools of Computing LLC”);
	\end{verbatim}
	
	\begin{verbatim}
	

        setLayout(new GridBagLayout());
	\end{verbatim}
	
	\begin{verbatim}
	

        GridBagConstraints gbc0 = new GridBagConstraints();
	\end{verbatim}
	
	\begin{verbatim}
	

        GridBagConstraints gbc = new GridBagConstraints();
	\end{verbatim}
	
	\begin{verbatim}
	

        gbc0.gridwidth = 1;
	\end{verbatim}
	
	\begin{verbatim}
	

        gbc.gridwidth = GridBagConstraints.REMAINDER;
	\end{verbatim}
	
	\begin{verbatim}
	

        to = new TextField(40);
	\end{verbatim}
	
	\begin{verbatim}
	

        to.setText(“gkt@gauss.jhpc.cs.depaul.edu”);
	\end{verbatim}
	
	\begin{verbatim}
	

        to.setText(“gkt@localhost”);
	\end{verbatim}
	
	\begin{verbatim}
	

        from = new TextField(40);
	\end{verbatim}
	
	\begin{verbatim}
	

        from.setText(“gkt@cs.depaul.edu”);
	\end{verbatim}
	
	\begin{verbatim}
	

        from.setText(“gkt@localhost”);
	\end{verbatim}
	
	\begin{verbatim}
	

        subject = new TextField(40);
	\end{verbatim}
	
	\begin{verbatim}
	

        subject.setText(“GEORGE MAIL: “ + new Date().toString());
	\end{verbatim}
	
	\begin{verbatim}
	

        smtpHost = new TextField(40);
	\end{verbatim}
	
	\begin{verbatim}
	

        smtpHost.setText(“gauss.jhpc.cs.depaul.edu”);
	\end{verbatim}
	
	\begin{verbatim}
	

        smtpHost.setText(“localhost”);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(new Label(“To:”),gbc0);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(to,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(new Label(“From:”),gbc0);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(from,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(new Label(“Subject:”),gbc0);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(subject,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(new Label(“SMTP Agent:”),gbc0);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(smtpHost,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        message = new TextArea(25,40);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(new Label(“Message”),gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(message,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        send = new Button(“Send”);
	\end{verbatim}
	
	\begin{verbatim}
	

        send.addActionListener(this);
	\end{verbatim}
	
	\begin{verbatim}
	

        add(send,gbc);
	\end{verbatim}
	
	\begin{verbatim}
	

        pack();
	\end{verbatim}
	
	\begin{verbatim}
	

        show();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void actionPerformed(ActionEvent ae) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (ae.getSource() == send) {
	\end{verbatim}
	
	\begin{verbatim}
	

            sendMail();
	\end{verbatim}
	
	\begin{verbatim}
	

            this.dispose();
	\end{verbatim}
	
	\begin{verbatim}
	

            System.exit(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void send(String command) throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        out.println(command);
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“<send> “ + command);
	\end{verbatim}
	
	\begin{verbatim}
	

        out.flush();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void receive() throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“<receive>”);
	\end{verbatim}
	
	\begin{verbatim}
	

        do {
	\end{verbatim}
	
	\begin{verbatim}
	

            int chi = in.read();
	\end{verbatim}
	
	\begin{verbatim}
	

            if (chi < 0) break;
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.print( (char) chi);
	\end{verbatim}
	
	\begin{verbatim}
	

        } while (in.ready());
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“</receive>”);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void sendMail() {
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            smtpConnection = new Socket(smtpHost.getText(),25);
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(“<general> Connected to “
	\end{verbatim}
	
	\begin{verbatim}
	

				+ smtpHost.getText() + “\n”);
	\end{verbatim}
	
	\begin{verbatim}
	

            OutputStream os = smtpConnection.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

            OutputStreamWriter osw = new OutputStreamWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

            out = new PrintWriter(osw);
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            InputStream is = smtpConnection.getInputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

            InputStreamReader isr = new InputStreamReader(is);
	\end{verbatim}
	
	\begin{verbatim}
	

            in = isr;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

                  String command;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            command = “EHLO jhpc.cs.depaul.edu”;
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            int msgLength = subject.getText().length()
	\end{verbatim}
	
	\begin{verbatim}
	

				+ message.getText().length() + “Subject: “.length();
	\end{verbatim}
	
	\begin{verbatim}
	

            command = “MAIL FROM: <“ + from.getText()
	\end{verbatim}
	
	\begin{verbatim}
	

				+ “> SIZE=”+msgLength;
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            command = “RCPT TO: <“ + to.getText() + “>”;
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            command = “DATA”;
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            command = “Subject: “ + subject.getText() + “\n” 
	\end{verbatim}
	
	\begin{verbatim}
	

				+ message.getText() + “\n” + “.”;
	\end{verbatim}
	
	\begin{verbatim}
	

            
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

            command = “QUIT”;
	\end{verbatim}
	
	\begin{verbatim}
	

            send(command);
	\end{verbatim}
	
	\begin{verbatim}
	

            receive();
	\end{verbatim}
	
	\begin{verbatim}
	

            smtpConnection.close();
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(“<general> “ +  e.toString());
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String args[]) {
	\end{verbatim}
	
	\begin{verbatim}
	

        SendMailSync sm = new SendMailSync();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
\subsubsection{Where are The Services?}

% Label
\label{pgfId-10002}

% Label
\label{pgfId-10212}
The foregoing discussion has been about SMTP, which is just one of many network services that are provided on your computer. As introduced earlier, a service is usually known by a common name, a protocol, and a port number. In Unix, the information about services is kept in the /etc/services file; Windows usually keeps this information in the registry.
\par

% Label
\label{pgfId-10213}
The notion of exposed services that are available on a computer lends itself nicely to another programming example, which we call
\texttt{PortScan}
(affectionately named after the port scanners and sniffers that are available on the market, usually used by prospective eavesdroppers). The code for this is provided in two parts, which are shown in
\ref{id(98474)}[MISSING HREF]
and
\ref{id(20185)}[MISSING HREF]
. The port scanner works by reading the /etc/services file, provided on all flavors of Unix, and a range of ports (low and high values) to be scanned. By iterating from the low to high values, an attempt is made to connect to the port. If the connection is successful, the port number is displayed, as well as the name of the service, if it corresponds to a well-known service; otherwise, nothing is displayed. Thus, the port scanner itself represents a very simple program overall.
\par

% Label
\label{pgfId-10255}
Let us now examine the code in a little more detail. The code shown in
\ref{id(98474)}[MISSING HREF]
is a handy class that mimics the functionality found in the Perl and Python language (and library) to split a character string, given a set of delimiters, into a list of fields. Recall that the lines of the /etc/services file have the following general structure
\par

% Label
\label{pgfId-10256}
\# service port/protocol
% Label
\label{pgfId-10257}
smtp 25/tcp
% Label
\label{pgfId-10258}
In Perl, it is possible to parse this information--quickly--using the intrinsic
\texttt{split()}
function, which even allows multiple delimiters to be specified:
\par

	\begin{verbatim}
	

\# Fragment of Perl code to quickly parse an input line into
	\end{verbatim}
	
	\begin{verbatim}
	

# multiple fields, given a set of delimiters (regular expression)
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

FP = open(“/etc/services”,”r”)
	\end{verbatim}
	
	\begin{verbatim}
	

while (<FP>) {
	\end{verbatim}
	
	\begin{verbatim}
	

	(service, port, protocol) = split(/ \/\n/)
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-10267}
Python also supports a similar notion, but does not permit multiple delimiters to be used to perform the split. The code is still fairly straightforward:
\par

	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

# Fragment of Python code to do the same thing:
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

import string
	\end{verbatim}
	
	\begin{verbatim}
	

fp = open(‘/etc/services’,’r’)
	\end{verbatim}
	
	\begin{verbatim}
	

allLines = fp.readlines()
	\end{verbatim}
	
	\begin{verbatim}
	

for line in allLines:
	\end{verbatim}
	
	\begin{verbatim}
	

	(service, pp) = string.split(line, ‘ \n’)
	\end{verbatim}
	
	\begin{verbatim}
	

	(port, protocol) = string.split(pp, ‘/\n’)
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
% Label
\label{pgfId-10287}
Although Java’s capabilities are very object oriented and customizable, Python and Perl provide a great deal more language-level (and library-level) support for tasks that often need to be performed on strings. Text-processing applications really demand the capabilities that are found in both of these languages.
\par

% Label
\label{pgfId-10289}
Recognizing the need, the the
\texttt{Splitter}
class shown in
\ref{id(98474)}[MISSING HREF]
was designed to support the same flexibility provided by Perl and Python, subject to the language limitations.
\par

% Label
\label{pgfId-10297}
A Splitter is constructed from a number of user-supplied values:
\par

\begin{itemize}

\item{Text : This is the initial string to be split. It is optional to specify the text at construction time; however, the text must be specified before any attempt to extract fields.}

% Label
\label{pgfId-10293}

\item{Labels : This is a set of character strings used to name the fields. Java does not permit you to have multiple variables on the left-hand side of an expression (list L -values). Using the labels, we can access fields of a string by name. The labels are optional. Fields can always be accessed by position, beginning with zero.}

% Label
\label{pgfId-10294}

\item{Delimiters : This is a set of characters that can be used to delimit the fields. If no delimiters are specified, whitespace delimiters (space, newline, and tab) are chosen by default.}

% Label
\label{pgfId-10300}

\end{itemize}

% Label
\label{pgfId-10301}
In addition to user-specified values, the splitter maintains a couple of private data structures to aid in performing the split and maintaining good performance:
\par

\begin{itemize}

\item{Tokens : These are contained in a Vector object of all tokens for the input line currently being processed.}

% Label
\label{pgfId-10305}

\item{Tokenizer : This is Java’s built-in StringTokenizer class that allows us to split strings according to a set of delimiters. This class does not keep track of all of the tokens and thus prevents true random access to the various tokens, hence the existence of the Splitter class.}

% Label
\label{pgfId-10306}

\end{itemize}

% Label
\label{pgfId-10307}
The
\texttt{Splitter}
class supports a number of methods. We only make use of one of these methods; however, for completeness, we discuss the key capabilities of this class, which is likely to be a useful companion in your toolbox of text-processing features:
\par

\begin{itemize}

\item{public String getTokenAt(int pos) : This returns the token a given position. Positions are numbered from zero. Thus, if you want the first field, you need to specify a parameter value of zero.}

% Label
\label{pgfId-10312}

\item{public String getTokenAt(String label) : This returns the token at a given label. The label is looked up in the list of labels, if they were provided by the user, and the index position is computed. For example, in the /etc/services input file, you could use getTokenAt(“service”) to return the value at that field’s position (0).}

% Label
\label{pgfId-10321}

\item{public void getAllTokens() : This simply returns a Vector object of all tokens to you; however, you should be careful to copy the vector if you need the results permanently, because a reference to the private vector is being returned and thus has the potential to be corrupted. This can easily be done with vector cloning (i.e., calling the clone() method).}

% Label
\label{pgfId-10322}

\item{public void setTokenAt(String token, int pos) : You can change the value of a particular field. This can be useful if you want the ability to put the string back together.}

% Label
\label{pgfId-10325}

\item{public String join(String before, String between, String after, boolean squash) : A string can be formed from the tokens. This is a feature supported in Python and Perl. You can also specify some “glue” to be pasted before the first token, after the last token, and between every pair of tokens.}

% Label
\label{pgfId-10326}

\end{itemize}

% Label
\label{pgfId-10327}
Thus, this class provides nearly 100% compatibility with the interfaces found in Python and Perl. We only make use of the
\texttt{getTokenAt()}
method in the code shown in
\ref{id(20185)}[MISSING HREF]
, which is the subject of the rest of this section.
\par

% Label
\label{pgfId-10302}

\par
Splitter: A Convenient Little Utility for Breaking up Input Lines
	\begin{verbatim}
	

package com.toolsofcomputing.text;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class Splitter {
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private String text;
	\end{verbatim}
	
	\begin{verbatim}
	

    private String delimiters;
	\end{verbatim}
	
	\begin{verbatim}
	

    private Vector tokens;
	\end{verbatim}
	
	\begin{verbatim}
	

    private StringTokenizer tokenizer;
	\end{verbatim}
	
	\begin{verbatim}
	

    private String labels[];
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Splitter(String[] labels, String text, 
	\end{verbatim}
	
	\begin{verbatim}
	

      String delimiters) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.text = text;
	\end{verbatim}
	
	\begin{verbatim}
	

        this.delimiters = delimiters;
	\end{verbatim}
	
	\begin{verbatim}
	

        tokens = new Vector();
	\end{verbatim}
	
	\begin{verbatim}
	

        tokenizer = null;
	\end{verbatim}
	
	\begin{verbatim}
	

        this.labels = labels;
	\end{verbatim}
	
	\begin{verbatim}
	

        performSplit();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Splitter(String text, String delimiters) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this(new String[0], text, delimiters);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Splitter(String[] labels, String delimiters) {
	\end{verbatim}
	
	\begin{verbatim}
	

        String defaultText = ““;
	\end{verbatim}
	
	\begin{verbatim}
	

        for (int i=0; i < labels.length; i++) {
	\end{verbatim}
	
	\begin{verbatim}
	

            defaultText += labels[i];
	\end{verbatim}
	
	\begin{verbatim}
	

            defaultText += delimiters.charAt(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        } 
	\end{verbatim}
	
	\begin{verbatim}
	

        this.text = defaultText;
	\end{verbatim}
	
	\begin{verbatim}
	

        this.delimiters = delimiters;
	\end{verbatim}
	
	\begin{verbatim}
	

        tokens = new Vector();
	\end{verbatim}
	
	\begin{verbatim}
	

        tokenizer = null;
	\end{verbatim}
	
	\begin{verbatim}
	

        this.labels = labels;
	\end{verbatim}
	
	\begin{verbatim}
	

        performSplit();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void setText(String text) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.text = text;
	\end{verbatim}
	
	\begin{verbatim}
	

        performSplit();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void setDelimiters(String delimiters) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.delimiters = delimiters;
	\end{verbatim}
	
	\begin{verbatim}
	

        performSplit();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void setTextAndDelimiters(String text,
	\end{verbatim}
	
	\begin{verbatim}
	

      String delimiters) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.text = text;
	\end{verbatim}
	
	\begin{verbatim}
	

        this.delimiters = delimiters;
	\end{verbatim}
	
	\begin{verbatim}
	

        performSplit();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void setLabels(String[] labels) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.labels = labels;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String getLabel(int index) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (labels == null || index < 0 || index >= labels.length)
	\end{verbatim}
	
	\begin{verbatim}
	

            return index + ““;
	\end{verbatim}
	
	\begin{verbatim}
	

        else
	\end{verbatim}
	
	\begin{verbatim}
	

            return labels[index];
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void performSplit() {
	\end{verbatim}
	
	\begin{verbatim}
	

        tokenizer = new StringTokenizer(text, delimiters);
	\end{verbatim}
	
	\begin{verbatim}
	

        tokens.removeAllElements();
	\end{verbatim}
	
	\begin{verbatim}
	

        while (tokenizer.hasMoreTokens()) {
	\end{verbatim}
	
	\begin{verbatim}
	

            tokens.addElement(tokenizer.nextToken());
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public int getTokenCount() {
	\end{verbatim}
	
	\begin{verbatim}
	

        return tokens.size();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String getTokenAt(int position) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (position >= 0 && position < tokens.size())
	\end{verbatim}
	
	\begin{verbatim}
	

            return (String)tokens.elementAt(position);
	\end{verbatim}
	
	\begin{verbatim}
	

        else
	\end{verbatim}
	
	\begin{verbatim}
	

            return null;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String getTokenAt(String label) {
	\end{verbatim}
	
	\begin{verbatim}
	

        int index = findLabel(label);
	\end{verbatim}
	
	\begin{verbatim}
	

        if (index < 0) {
	\end{verbatim}
	
	\begin{verbatim}
	

            try {
	\end{verbatim}
	
	\begin{verbatim}
	

                index = Integer.parseInt(label);
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch(NumberFormatException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

                return null;
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        return getTokenAt(index);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private int findLabel(String label) {
	\end{verbatim}
	
	\begin{verbatim}
	

        int index;
	\end{verbatim}
	
	\begin{verbatim}
	

        for (index=0; index < labels.length; index++)
	\end{verbatim}
	
	\begin{verbatim}
	

            if (label.equals(labels[index]))
	\end{verbatim}
	
	\begin{verbatim}
	

                return index;
	\end{verbatim}
	
	\begin{verbatim}
	

        return -1;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Vector getAllTokens() {
	\end{verbatim}
	
	\begin{verbatim}
	

        return tokens;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void setTokenAt(String text, int position) {
	\end{verbatim}
	
	\begin{verbatim}
	

        tokens.setElementAt(text, position);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String toString() {
	\end{verbatim}
	
	\begin{verbatim}
	

        int i;
	\end{verbatim}
	
	\begin{verbatim}
	

        String s = ““;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        for (i=0; i < getTokenCount(); i++) {
	\end{verbatim}
	
	\begin{verbatim}
	

            if (i > 0)
	\end{verbatim}
	
	\begin{verbatim}
	

                s = s + “\n”;
	\end{verbatim}
	
	\begin{verbatim}
	

      
	\end{verbatim}
	
	\begin{verbatim}
	

            s = s + “[“ + getLabel(i) + “] = “ + getTokenAt(i);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        return s;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-10334}
The
\texttt{PortScan}
code itself is fairly straightforward. In truth, we probably do not need to create an object to perform the scanning operation, since this class only peforms a single function: scanning a range of ports.
\par

% Label
\label{pgfId-10354}
The constructor is where we make use of the
\texttt{Splitter}
class that was discussed earlier. We build on a concept that was presented earlier, called stream layering. The biggest challenge in working with Java streams is to find the class that can perform a function that is needed. The
\texttt{FileReader}
class allows us to open a file for input. We layer a
\texttt{BufferedReader}
instance atop the
\texttt{FileReader}
so we can read a single line of input at a time, since the services file is an ASCII text file of a line-oriented nature. Once the line of input is read, the
\texttt{Splitter}
class is put to work, so a hash table of all predefined services can be built.
\texttt{Hashtable}

\texttt{services}
maintains an association between a port number (contained in a character string) and a service name (also contained in a character string). That’s all the constructor does.
\par

% Label
\label{pgfId-10355}
The
\texttt{scan()}
method has been designed to allow multiple scans to be performed. An iteration is performed from the low to the high port values that were specified by the user. For each value, an attempt is made to open a socket to the service. This code is contained in a
\texttt{try}
-
\texttt{catch}
block, because many attempts are going to result in exceptions, since there is simply no service running on that port. When a
\texttt{Socket}
instance is successfully created, the port is looked up in
\texttt{services}
, and if the port is found, the name of the service is printed. If the port is not found, it is listed as an unknown service. In the case where a socket was successfully opened, the connection is closed at the end to ensure that system resources are not being wasted. (Sockets are IPC mechanisms, and most systems do have hard limits on how many of a particular resource can be used at a particular time, although the number is usually quite large.)
\par

% Label
\label{pgfId-10379}

\par
PortScan.java: scan a range of ports for standard (and other) services
	\begin{verbatim}
	

package com.toolsofcomputing.networking;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

import com.toolsofcomputing.text.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class PortScan {
	\end{verbatim}
	
	\begin{verbatim}
	

    private Hashtable services;
	\end{verbatim}
	
	\begin{verbatim}
	

    public static String[] serviceLabels = {“service”,“pinfo” };
	\end{verbatim}
	
	\begin{verbatim}
	

    public static String[] portInfoLabels = { “port”, “proto” };
	\end{verbatim}
	
	\begin{verbatim}
	

    private Splitter lineSplitter;
	\end{verbatim}
	
	\begin{verbatim}
	

    private Splitter portInfoSplitter;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public PortScan(String servicesFile) throws Exception {
	\end{verbatim}
	
	\begin{verbatim}
	

        FileReader fr = new FileReader(servicesFile);
	\end{verbatim}
	
	\begin{verbatim}
	

        BufferedReader br = new BufferedReader(fr);
	\end{verbatim}
	
	\begin{verbatim}
	

        String inLine;
	\end{verbatim}
	
	\begin{verbatim}
	

        lineSplitter = new Splitter(serviceLabels,” \t\n”);
	\end{verbatim}
	
	\begin{verbatim}
	

        portInfoSplitter = new Splitter(portInfoLabels,”/”);
	\end{verbatim}
	
	\begin{verbatim}
	

        services = new Hashtable();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        while (true) {
	\end{verbatim}
	
	\begin{verbatim}
	

            inLine = br.readLine();
	\end{verbatim}
	
	\begin{verbatim}
	

            if (inLine == null) break;
	\end{verbatim}
	
	\begin{verbatim}
	

            if (inLine.startsWith(“#”)) continue;
	\end{verbatim}
	
	\begin{verbatim}
	

            lineSplitter.setText(inLine);
	\end{verbatim}
	
	\begin{verbatim}
	

            String service = lineSplitter.getTokenAt(“service”);
	\end{verbatim}
	
	\begin{verbatim}
	

            String portinfo = lineSplitter.getTokenAt(“pinfo”);
	\end{verbatim}
	
	\begin{verbatim}
	

            if (portinfo == null) continue;
	\end{verbatim}
	
	\begin{verbatim}
	

            portInfoSplitter.setText(portinfo);
	\end{verbatim}
	
	\begin{verbatim}
	

            String port = portInfoSplitter.getTokenAt(“port”);
	\end{verbatim}
	
	\begin{verbatim}
	

            String protocol =
	\end{verbatim}
	
	\begin{verbatim}
	

              portInfoSplitter.getTokenAt(“proto”);
	\end{verbatim}
	
	\begin{verbatim}
	

            if (protocol.equals(“tcp”))
	\end{verbatim}
	
	\begin{verbatim}
	

                services.put(port,service);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void scan(String host, int lo, int hi) {
	\end{verbatim}
	
	\begin{verbatim}
	

        int count=0;
	\end{verbatim}
	
	\begin{verbatim}
	

        for (int port=lo; port <= hi; port++) {
	\end{verbatim}
	
	\begin{verbatim}
	

            count++;
	\end{verbatim}
	
	\begin{verbatim}
	

            if (count % 1000 == 0)
	\end{verbatim}
	
	\begin{verbatim}
	

                System.out.println(“Tested “ + count + “ ports.”);
	\end{verbatim}
	
	\begin{verbatim}
	

            try {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s = new Socket(host, port);
	\end{verbatim}
	
	\begin{verbatim}
	

                String service = (String)services.get(port + ““);
	\end{verbatim}
	
	\begin{verbatim}
	

                if (service != null)
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.out.println(port + “ -> “ + service);
	\end{verbatim}
	
	\begin{verbatim}
	

                else
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.out.println(port + “...unknown”);
	\end{verbatim}
	
	\begin{verbatim}
	

                s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String args[]) {
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            PortScan ps = new PortScan(“/etc/services”);
	\end{verbatim}
	
	\begin{verbatim}
	

            ps.scan(args[0],
	\end{verbatim}
	
	\begin{verbatim}
	

              Integer.parseInt(args[1]),
	\end{verbatim}
	
	\begin{verbatim}
	

              Integer.parseInt(args[2]));
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(e);
	\end{verbatim}
	
	\begin{verbatim}
	

            e.printStackTrace();
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-10459}
It is interesting to run this program to see the results against typical Windows and Unix configurations. We ran the program against our laboratory machines. The most obvious difference between the two is that more services are running on Unix than on Windows. This is not to insinuate that Windows is an inferior technology; however, out of the box, Windows definitely does not come configured with nearly as many useful services as Unix. The authors here are aware of a number of interesting claims made pertaining to Windows and Unix security, wherein Windows is claimed to have higher security. This argument certainly holds true if you limit the discussion to the number of services and ignore how the services are configured. The more services that there are running, the more susceptible you are to attack. Our Windows setup, however, is not representative of a truly typical Windows setup, wherein a few services are added, such as SMTP (provide by Microsoft Exchange Server), web service (provided by Internet Information Server), and a remote-terminal capability, usually provided by VNC or Citrix products.
\par

	%\begin{tabular}
	
% Label
\label{pgfId-10383}
Output on a Typical Linux Setup (Workstation)
	\begin{verbatim}
	

22 -> ssh
	\end{verbatim}
	
	\begin{verbatim}
	

23 -> telnet
	\end{verbatim}
	
	\begin{verbatim}
	

25 -> smtp
	\end{verbatim}
	
	\begin{verbatim}
	

80 -> www
	\end{verbatim}
	
	\begin{verbatim}
	

98 -> linuxconf
	\end{verbatim}
	
	\begin{verbatim}
	

111 -> sunrpc
	\end{verbatim}
	
	\begin{verbatim}
	

113 -> auth
	\end{verbatim}
	
	\begin{verbatim}
	

139 -> netbios-ssn
	\end{verbatim}
	
	\begin{verbatim}
	

389 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

515 -> printer
	\end{verbatim}
	
	\begin{verbatim}
	

789 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

794 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

970 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

Tested 1000 ports.
	\end{verbatim}
	
	\begin{verbatim}
	

1024 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1025 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1029 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1033 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1034 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1035 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

1036 found but unknown service
	\end{verbatim}
	
	\begin{verbatim}
	

Tested 2000 ports.
	\end{verbatim}
	
	\begin{verbatim}
	

Tested 3000 ports.
	\end{verbatim}
	
	\begin{verbatim}
	

3306 -> mysql
	\end{verbatim}
	
	\begin{verbatim}
	

Tested 4000 ports.
	\end{verbatim}
	
	\begin{verbatim}
	

Tested 5000 ports.
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	%\end{tabular}
	
% Label
\label{pgfId-7235}
In both cases, observe that a number of ports are registering as unknown services. This is not completely true.
\ref{#id(pgfId-14374)}[MISSING HREF]
Some of these services actually correspond to user programs that are listening on a particular port for incoming connections or possibly detached processes that have allocated a port for a callback from a remote server. Thus, the port scanner should be construed as the “first call” to identify candidate ports for further exploration. To find out what is running (in general), you need to attempt to commnicate with the services that have been discovered by sending protocol messages or commands to perturb the service and (hopefully) get the service to “talk” to you.
\par

	%\begin{tabular}
	
% Label
\label{pgfId-10443}
Output on a Typical Windows NT Setup (Server)Output Against a Windows NT 4.0 Setup
% Label
\label{pgfId-10447}
135 found but unknown service
% Label
\label{pgfId-10448}
139 -> netbios-ssn
% Label
\label{pgfId-10449}
Tested 1000 ports.
% Label
\label{pgfId-10450}
1032 found but unknown service
% Label
\label{pgfId-10451}
Tested 2000 ports.
% Label
\label{pgfId-10452}
Tested 3000 ports.
% Label
\label{pgfId-10453}
Tested 4000 ports.
	\begin{verbatim}
	

Tested 5000 ports.
	\end{verbatim}
	
	%\end{tabular}
	
\section{A Kind and Gentle Introduction to the Server Side}

% Label
\label{pgfId-10467}

% Label
\label{34588}

% Label
\label{pgfId-10624}

\ref{id(34842)}[MISSING HREF]
depicts a typical client-server networking setup. This setup represents the typical architecture of most message-passing schemes one will encounter that are based on sockets.
\par
Typical Client-Server Setup in Java
% Label
\label{pgfId-10551}

% Beginning of DIV

\includegraphics{figures/networking-1}

% End of DIV

% Label
\label{pgfId-10553}
There are four general steps to be performed in a typical clients-server environment:
\par

% Label
\label{pgfId-10639}
1. The client initates contact with the server.
\par

% Label
\label{pgfId-10630}
2. The server listens for and accepts client connections.
\par

% Label
\label{pgfId-10641}
3. The server (optionally) allocates a thread to communicate with the client.
\par

% Label
\label{pgfId-10642}
4. Business is conducted.
\par

\subsubsection{Iterative Servers}

% Label
\label{pgfId-10898}

% Label
\label{pgfId-10912}

\ref{id(11917)}[MISSING HREF]
contains the source code for a date-and-time server (class
\texttt{DateTimeServer}
), which is similar to the date-and-time service found in the Unix operating system. It is an example of an iterative server, which is a server that accepts requests one at a time and processes them fully, much like loop iterations in which each iteration of the loop passes through the body of the loop and executes fully (unless, of course, you have parallelized the iterations as we discussed in the chapter on parallel loops.)
\par

% Label
\label{pgfId-10923}
Let us now consider the details of class
\texttt{DateTimeServer}
. This is the first example in which we make use of the
\texttt{ServerSocket}
class.
\texttt{ServerSocket}
is provided in the java.net package (with the
\texttt{Socket}
and
\texttt{InetAddress}
classes we presented earlier) and is a useful building block for building internet services. The
\texttt{ServerSocket}
class differs from
\texttt{Socket}
in its ability to accept incoming connections from clients. This is done using the
\texttt{accept()}
method, as shown in the code. When an incoming connection is accepted, a connection is obtained, and a reference to a
\texttt{Socket}
instance is returned. Once this reference is obtained, communication can be performed with the client and (once the communication has been completed), another connection can be accepted.
\par
Iterative Date-and-Time Server
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

class DateTimeServer {
	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String[] args){
	\end{verbatim}
	
	\begin{verbatim}
	

        if (args.length<1) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(“usage: java DayTimeServer port”);
	\end{verbatim}
	
	\begin{verbatim}
	

            System.exit(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        try{
	\end{verbatim}
	
	\begin{verbatim}
	

            int port = Integer.parseInt(args[0]);
	\end{verbatim}
	
	\begin{verbatim}
	

            ServerSocket ssock=new ServerSocket(port);
	\end{verbatim}
	
	\begin{verbatim}
	

            for(;;) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=ssock.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                OutputStream os = s.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

                PrintWriter out=new PrintWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

                Date d = new Date();
	\end{verbatim}
	
	\begin{verbatim}
	

                out.println(d);
	\end{verbatim}
	
	\begin{verbatim}
	

                out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (IOException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-10927}
The real work in the code is done in a section known as the server loop. A server loop is almost always an infinite loop and is used in all distributed object systems, such as remote method invocation (RMI) and common object request broker architecture (CORBA). Let’s study the details of the server loop a little more closely:
\par

	\begin{verbatim}
	

           for(;;) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=ssock.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                OutputStream os = s.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

                PrintWriter out=new PrintWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

                Date d = new Date();
	\end{verbatim}
	
	\begin{verbatim}
	

                out.println(d);
	\end{verbatim}
	
	\begin{verbatim}
	

                out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
% Label
\label{pgfId-10948}
The
\texttt{for(;;)}
loop header indicates that there is no initialization condition, no termination condition, and no increment peformed at the end of a loop iteration. This is the preferred way to setup infinite loops in Java (and C and C++ for that matter). You could equivalently do this with a
\texttt{while(true)}
loop header. The
\texttt{accept()}
method is called on the server socket
\emph{ssock}
and is an example of a call that
\emph{blocks}
indefinitely. We’ll return to a discussion of blocking and its advantages and disadvantages shortly. Once the connection has been accepted, the
\texttt{getOutputStream()}
method gives you a handle for communication on the socket. Although we are not accepting input on this socket, note that there is no fundamental limitation on what you can do with respect to communication. Sockets in Java allow you to obtain both an
\texttt{InputStream}
and an
\texttt{OutputStream}
for communication. By obtaining an OutputStream (rememer that this is the server side of the picture), we are able to write output to the client. We layer a
\texttt{PrintWriter}
instance on top of the
\texttt{OutputStream}
in order to perform higher level output functions.
\texttt{PrintWriter}
is Java’s way of giving you the ability to do formatted output in much the same fashion is C’s
\texttt{printf()}
function, with the notable difference of being completely safe. We use
\texttt{println()}
to send the
\texttt{Date}
instance
\texttt{d}
to the output stream, which writes the string representation of
\texttt{d}
, followed by a newline.
\par

% Label
\label{pgfId-10955}
The box
\ref{id(70713)}[MISSING HREF]
provides a little insight on character strings and Java, since we are taking advantage of some tricks that may not be familiar to programmers who are coming from a C or FORTRAN background.
\par

	%\begin{tabular}
	
% Label
\label{pgfId-10962}

% Label
\label{70713}
Strings and Java
	\begin{verbatim}
	

Programmers who grew up on C or FORTRAN often find Java’s built-in support for strings a bit confusing. Although Java makes string processing ever so much easier, its close integration with the language can be a bit disconcerting.
	\end{verbatim}
	
	\begin{verbatim}
	

All Java classes are either direct or indirect descendents of the 
Object
 class. This means that a 
toString()
 method is inherited. The purpose of this function is to return a string representation of the class, which is ideal for debugging, as well as for easy conversion to a printable representation. In situations where a 
String
 is required, any attempt to pass an 
Object
 (or subclass thereof) will result in the 
toString()
 method being called. This is actually done in our 
DateTimeServer
 example, where the 
Date
 instance 
d
 is converted into a 
String
 when passed to the 
println()
 method.
	\end{verbatim}
	
	\begin{verbatim}
	

The ability to convert any object to a string is also exploited in  string concatenation. String concatenation is supported as an intrinsic operation in Java with a specially overloaded 
+
 operator. When any attempt is made to include an object in a concaenation expression, such as “s + object” or “object + s”, the object will be converted to a string (using its 
toString()
 method). Then, the string representation will be concatenated with the other string.
	\end{verbatim}
	
	\begin{verbatim}
	


String
 is just one of a few classes in Java that straddles the fine line between being a built-in primitive type and a part of the library. For all practical purposes, however, it will be necessary to learn the methods provided by the string class, since it is not possible to perform operations on strings as found in C, such as subscripting, with array-like syntax.
	\end{verbatim}
	
	%\end{tabular}
	
% Label
\label{pgfId-10989}
Iterative servers, such as the one shown in the
\texttt{DateTimeServer}
example, should only be used in situations where the body of the server loop executes very quickly. The date-and-time service happens to be a good example of such a service. Later, we will show examples of where the amount of time to execute the body is either of longer duration or unknown, in which case it will be necessary to dispatch a thread to handle the incoming connection and perform the service.
\ref{id(32267)}[MISSING HREF]
shows how we can extend the iterative server to concurrently accept connections and perform the service. We realize that for such a simple service it does not make complete sense to create threads for this purpose; however, the intention is to demonstrate how to make the same code concurrent and exists primarily for pedagogical reasons. This same idea will be used to construct a much more general (and complex) services framework later, so we urge you not to rush to judgment quickly about this example being too simple minded in nature.
\par

% Label
\label{pgfId-11003}
The
\texttt{ThreadedDateTimeServer}
class is very similar to the earlier example; however, a key difference is that we actually need to create an object for each connection made by clients. This example actually follows the general client-server scenario that was presented earlier in
\ref{id(34842)}[MISSING HREF]
. We will now discuss the code in two parts. First, we discuss the details of the server loop, which is followed by a discussion of the
\texttt{run()}
method, which carries out the date-and-time service.
\par

% Label
\label{pgfId-14475}

\par
Concurrent Date-and-Time Server
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class ThreadedDateTimeServer extends Thread {
	\end{verbatim}
	
	\begin{verbatim}
	

    private Socket s;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public ThreadedDateTimeServer(Socket s) {
	\end{verbatim}
	
	\begin{verbatim}
	

        this.s = s;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String[] args){
	\end{verbatim}
	
	\begin{verbatim}
	

        if (args.length<1) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println
          (“usage: java ThreadedDateTimeServer port”);
	\end{verbatim}
	
	\begin{verbatim}
	

            System.exit(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        try{
	\end{verbatim}
	
	\begin{verbatim}
	

            int port = Integer.parseInt(args[0]);
	\end{verbatim}
	
	\begin{verbatim}
	

            ServerSocket listener = new ServerSocket(port);
	\end{verbatim}
	
	\begin{verbatim}
	

            for(;;) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=listener.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                Thread server = new ThreadedDateTimeServer(s);
	\end{verbatim}
	
	\begin{verbatim}
	

                server.start();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (IOException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void run() {
	\end{verbatim}
	
	\begin{verbatim}
	

        try{
	\end{verbatim}
	
	\begin{verbatim}
	

            OutputStream os = s.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

            PrintWriter out=new PrintWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

            Date d = new Date();
	\end{verbatim}
	
	\begin{verbatim}
	

            out.println(d);
	\end{verbatim}
	
	\begin{verbatim}
	

            out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (IOException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-10868}
The server loop is always required when implementing a service. This is because requests must be accepted one at a time and processed:
\par

	\begin{verbatim}
	

            for(;;) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=listener.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                Thread server = new ThreadedDateTimeServer(s);
	\end{verbatim}
	
	\begin{verbatim}
	

                server.start();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
% Label
\label{pgfId-11030}
As in the
\texttt{DateTimeServer}
iterative server, the
\texttt{accept()}
call is used to accept an incoming connection from the client. This time, however, instead of performing the service immediately, a thread is created to do the actual processing and return the date and time to the client. The
\texttt{Socket}
reference
\texttt{s}
is passed to the constructor used to initialize the thread reference (server).
\par

% Label
\label{pgfId-11050}
You can inspect the code from the body of the iterative date server’s server loop; the same exact code is used to return the results to the client. The only difference is that the entire body of the earlier loop (following the
\texttt{accept()}
call) has been moved into the
\texttt{run()}
method, with the only notable difference being a surrounding
\texttt{try}
-
\texttt{catch}
block.
\par

	\begin{verbatim}
	

    public void run() {
	\end{verbatim}
	
	\begin{verbatim}
	

        try{
	\end{verbatim}
	
	\begin{verbatim}
	

            OutputStream os = s.getOutputStream();
	\end{verbatim}
	
	\begin{verbatim}
	

            PrintWriter out=new PrintWriter(os);
	\end{verbatim}
	
	\begin{verbatim}
	

            Date d = new Date();
	\end{verbatim}
	
	\begin{verbatim}
	

            out.println(d);
	\end{verbatim}
	
	\begin{verbatim}
	

            out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (IOException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
% Label
\label{pgfId-11034}
The ability to easily make a concurrent server is what makes Java ideal for network programming. As we’ll see shortly, this pair of examples can be used to generalize a services framework for doing client-server programming with sockets. The remainder of this chapter is dedicated to showing how we can build a general-purpose peer-to-peer messaging architecture that supports bidirectional communication. We’ll use this messaging framework to reimplement the date-and-time service and then (in the next chapter) show how to evolve this framework in to a distributed framework and demonstrate the potential for scaling the techniques presented throughout the book to the network.
\par

% Label
\label{pgfId-11069}
Before proceeding to the discussion of the services framework, it is important to consider when to use (and not to use) threads in a networked context. The challenge of using threads is that there is a trade-off to be made between the execution time of the service and the cost of creating a thread. Even without doing a performance analysis of the preceding code, it is abundantly clear that the cost of creating a date object and turning it into a string is very low. The cost of creating a thread is not so expensive on most operating systems; however, compared with the cost of computing and returning the date, it is expensive. Thus, it is very important to think about these costs and how to optimize. One way to strike a balance is to use the
\texttt{RunQueue}
abstraction presented in an earlier chapter. This allows you to create a working “pool” of threads that are responsible for performing the actual service without having to incur the cost of creating and destroying threads every time the service is performed. The code for a date-and-time server that employs a run queue to concurrently dispatch requests is shown in
\ref{id(54139)}[MISSING HREF]
.
\par
RunQueueDateTimeServer
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

class RunQueueDateTimeServer {
	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String[] args){
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        if (args.length<1) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(“usage: java DayTimeServer port”);
	\end{verbatim}
	
	\begin{verbatim}
	

            System.exit(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        RunQueue dispatchQueue = new RunQueue(10,5);
	\end{verbatim}
	
	\begin{verbatim}
	

        try{
	\end{verbatim}
	
	\begin{verbatim}
	

            int port = Integer.parseInt(args[0]);
	\end{verbatim}
	
	\begin{verbatim}
	

            ServerSocket ssock=new ServerSocket(port);
	\end{verbatim}
	
	\begin{verbatim}
	

            for(;;) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=ssock.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                DateTimeRunnable dtr = new DateTimeRunnable(s);
	\end{verbatim}
	
	\begin{verbatim}
	

                dispatchQueue.put(dtr);
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (IOException e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            dispatchQueue.terminate();
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private static class DateTimeRunnable implements Runnable {
	\end{verbatim}
	
	\begin{verbatim}
	

        Socket s;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        public DateTimeRunnable(Socket s) {
	\end{verbatim}
	
	\begin{verbatim}
	

            this.s = s;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        public void run() {
	\end{verbatim}
	
	\begin{verbatim}
	

            try{
	\end{verbatim}
	
	\begin{verbatim}
	

                PrintWriter out;
	\end{verbatim}
	
	\begin{verbatim}
	

                out = new PrintWriter(s.getOutputStream());
	\end{verbatim}
	
	\begin{verbatim}
	

                out.println(new Date());
	\end{verbatim}
	
	\begin{verbatim}
	

                out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                s.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

                return;
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-11132}
In the foregoing example, the body of the loop is turned into the body of the
\texttt{run()}
method in a nested class
\texttt{(DateTimeRunnable)}
that implements the
\texttt{Runnable}
interface. The
\texttt{main()}
method of this example only differs in the following manner:
\par

\begin{itemize}

\item{The construction of a RunQueue instance: We have instantiated RunQueue dispatchQueue with a maximum number of threads (10) and maximum number of waiting threads (5).}

% Label
\label{pgfId-11147}

\item{The construction of a DateTimeRunnable object that is placed on dispatchQueue using the put() method.}

% Label
\label{pgfId-11148}

\end{itemize}

% Label
\label{pgfId-11149}
As finding the date and time is a very simple service, there really is no need to create so many threads. We have set values of 10 and 5 in anticipation of fairly light usage. Real services may need more control of these parameters. When we discuss the
\texttt{MessageServer}
, the service being implemented will be given more control of these parameters.
\par

% Label
\label{pgfId-14011}
An interesting question arises: Is this a good use of the run queue? One of the goals in using the run queue was to minimize the cost of thread creation. We have only partly addressed this problem, since we still have the overhead of creating an instance of
\texttt{DateTimeRunnable}
. (Recall that in
\ref{id(32267)}[MISSING HREF]
, we had to create an instance of
\texttt{ThreadedDateTimeServer}
.) Although we still have the overhead of object creation, we no longer have the additional overhead of starting a new thread and cleaning up after it, since the run queue maintains a working pool of threads.
\par

\section{Simple Messaging Architecture}

% Label
\label{pgfId-11443}

% Label
\label{42061}

% Label
\label{pgfId-12030}
The story of the Internet is fundamentally about client-server services. This is particularly apparent when you look closely at the most common services. In the foregoing discussion, we focused on the date-and-time service, which provides an excellent teaching example. Recognizing the importance of being able to develop Internet services easily, we have devised a simple framework for developing client-server networked applications, which you can use without modifications to make your own Internet services and clients.
\ref{id(14882)}[MISSING HREF]
shows an interaction diagram involving the various components of a client-server messaging system, which are as follows:
\par

% Label
\label{pgfId-12081}

\textbf{\texttt{Message}}
Message: A class used to describe a basic unit of communication. All communication between components is done via
\texttt{Message}
instances.
\par

% Label
\label{pgfId-12082}

\textbf{\texttt{Deliverable}}
Deliverable: An interface implemented by any class (usually on the server side) to indicate that a particular object is interested in receiving messages. We refer to this relationship as a subscription, which is a common design pattern. Only classes that implement the
\texttt{Deliverable}
interface may subscribe to messages via a
\texttt{MessageServer}
instance.
\par

% Label
\label{pgfId-12083}

\textbf{\texttt{MessageServer}}
MessageServer: A class used to factor out the common functionality of a server. The guts of this class are similar to the
\texttt{DateTimeServer}
but generalized for the purpose of accommodating a multitude of services.
\par

% Label
\label{pgfId-14479}

\textbf{\texttt{MessageClient}}
MessageClient: A class used to factor out the common functionality of a client. The guts of this class are similar to the
\texttt{DateTimeClient}
but generalized as in the case of the
\texttt{MessageServer}
.
\par
Simple Messaging Architecture (Interaction Diagram)
% Beginning of DIV

\includegraphics{figures/networking-2}

% End of DIV

% Label
\label{pgfId-14519}
Thus, simple messaging architecture (SMA) can be thought of as a very general-purpose set of class libraries for building your own client-server applications.
\par

% Label
\label{pgfId-12090}
Let us now consider the various components in detail.
\par

\subsubsection{The Message Class}

% Label
\label{pgfId-12095}

% Label
\label{pgfId-11817}
The core class used in SMA is the
\texttt{Message}
class.
\ref{#id(pgfId-14346)}[MISSING HREF]
A message is an abstraction that is built using a hash table, wherein the keys and values are
\texttt{String}
instances. Users of the
\texttt{Message}
class for all practical purposes think that they are working with something very similar to a hash table; however, a key difference between the
\texttt{Hashtable}
and the
\texttt{Message}
abstraction is that
\texttt{Hashtable}
instances can hold arbitrary objects as keys and values. This works very well for most applications, but can sometimes be very unfriendly for developing Internet services, which (to this day) predominantly make use of primitive data types (i.e., integer, float, and double) and character strings.
\par

% Label
\label{pgfId-11831}
The
\texttt{Message}
class demonstrates an example of the power of OOP. OOP allows you to separate the interface from the implementation. Users think that a message is nothing more than a specialized hash table that allows them to work with data types that are commonly used. The implementation actually handles the details of translating the user view into a suitable representation for transmission on the network.
\par

% Label
\label{pgfId-11832}

\ref{id(77785)}[MISSING HREF]
presents the code for the
\texttt{Message}
class. The following attributes are defined in this class (there are others, however, but these are the essential ones):
\par

\begin{itemize}

\item{parameters : This is a Hashtable object of user-specified parameters. A parameter is nothing more than a <key,value> association.}

% Label
\label{pgfId-11858}

\item{type : Every message has a type (an integer). This field is used to provide a quick way of determining what remote service is being accessed. By default, the value of zero is supplied.}

% Label
\label{pgfId-11864}

\item{tag : Every message can also specify an optional tag (an integer). The concept of a tag is intended as a flag in case there is a need to have a second criterion (other than the type field) for selecting a message. We will not be making use of it in the examples of this chapter. Think of it as a field that is reserved for future use.}

% Label
\label{pgfId-11867}

\item{rep : This is the packed representation of the Message (an array of characters). Method pack() is used to encode parameters into the packed representation.}

% Label
\label{pgfId-11895}

\item{length : This is the number of characters in the encoded representation.}

% Label
\label{pgfId-11870}

\end{itemize}

% Label
\label{pgfId-11918}
The key methods in the
\texttt{Message}
class include the following:
\par

% Label
\label{pgfId-11922}
Constructors:
\par

\begin{itemize}

\item{Message() : This constructs an empty Message instance. The message has no type, no tag, and no parameters.}

% Label
\label{pgfId-11919}

\item{Message(char[] packedRep) : This constructs a Message instance from a previously packed message representation. An invalid representation will result in an Exception being thrown.}

% Label
\label{pgfId-11917}

\item{pack() : This prepares the representation of the message for transmission over the network. This representation will be accessible via the rep attribute.}

% Label
\label{pgfId-11923}

\item{unpack() : This unpacks the representation presently being referenced by rep into parameters . This results in the previous value of parameters being completely clobbered.}

% Label
\label{pgfId-11924}

\end{itemize}

% Label
\label{pgfId-11928}
There are a number of additional methods provided, such as accessor (get and set) methods, as well as a number of private methods (used for implementating the
\texttt{pack()}
and
\texttt{unpack()}
functions). These will not be discussed here; however, there are two rather important methods that will be discussed that are used to read and write methods from
\texttt{Reader}
and
\texttt{Writer}
character streams, respectively:
\par

\begin{itemize}

\item{static Message getMessage(Reader in) : This (factor) method allows us to return Message instances directly from an underlying stream. For this method to work correctly it is assumed that the stream has been written (using the companion method putMessage() , which writes the packed representation to a Writer stream).}

% Label
\label{pgfId-11930}

\item{void putMessage(Writer out) : This method allows us to write the packed representation of a Message to a Writer stream to potentially be read again later via a call to getMessage() .}

% Label
\label{pgfId-12910}

\end{itemize}

% Label
\label{pgfId-11929}
These two methods can work in harmony to allow client-server communication in terms of messages, which is significantly easier than working with arrays of characters (the normal case for sockets programming). SMA uses
\texttt{Message}
instances for all communication between peers (the
\texttt{MessageServer}
and
\texttt{MessageClient}
classes).
\par

% Label
\label{pgfId-12911}

\par
Message
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class Message  {
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_ANY = 0;
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_INTEGER = 1;
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_REAL = 2;
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_STRING = 3;
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_BOOLEAN = 4;
	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int T_UNDEFINED = 5;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private Hashtable parameters = new Hashtable();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private int type = 0;
	\end{verbatim}
	
	\begin{verbatim}
	

    private int tag = 0;
	\end{verbatim}
	
	\begin{verbatim}
	

    private int length = 0;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private static final int HEADER_SIZE = 3;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private char[] rep;
	\end{verbatim}
	
	\begin{verbatim}
	

    private int repIndex = 0;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private StringBuffer sb = new StringBuffer();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Message(char[] packedRep) {
	\end{verbatim}
	
	\begin{verbatim}
	

        rep = packedRep;
	\end{verbatim}
	
	\begin{verbatim}
	

        unpack();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Message() {
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static Message getMessage(Reader in) throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        int messageLength = (int) in.read();
	\end{verbatim}
	
	\begin{verbatim}
	

        if (messageLength < 0)
	\end{verbatim}
	
	\begin{verbatim}
	

            throw new IOException();
	\end{verbatim}
	
	\begin{verbatim}
	

        char[] buf = new char[messageLength];
	\end{verbatim}
	
	\begin{verbatim}
	

        int bytesRead = in.read(buf,0,messageLength);
	\end{verbatim}
	
	\begin{verbatim}
	

        if (messageLength != bytesRead)
	\end{verbatim}
	
	\begin{verbatim}
	

            throw new IOException();
	\end{verbatim}
	
	\begin{verbatim}
	

        return new Message(buf);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void putMessage(Writer out) throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        pack();
	\end{verbatim}
	
	\begin{verbatim}
	

        out.write(rep.length);
	\end{verbatim}
	
	\begin{verbatim}
	

        out.write(rep);
	\end{verbatim}
	
	\begin{verbatim}
	

        out.flush();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

    public void setParam(String key, String value) {
	\end{verbatim}
	
	\begin{verbatim}
	

        parameters.put(key,value);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String getParam(String key) {
	\end{verbatim}
	
	\begin{verbatim}
	

        return (String) parameters.get(key);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public char[] getCharArray() {
	\end{verbatim}
	
	\begin{verbatim}
	

        pack();
	\end{verbatim}
	
	\begin{verbatim}
	

        return rep;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void putInt(int value) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (repIndex < rep.length)
	\end{verbatim}
	
	\begin{verbatim}
	

            rep[repIndex++] = (char) value;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void putParameter(String k, String v) {
	\end{verbatim}
	
	\begin{verbatim}
	

        putString(k);
	\end{verbatim}
	
	\begin{verbatim}
	

        putString(v);
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private void putString(String s) {
	\end{verbatim}
	
	\begin{verbatim}
	

        putInt(s.length());
	\end{verbatim}
	
	\begin{verbatim}
	

        putInt(T_STRING);
	\end{verbatim}
	
	\begin{verbatim}
	

        char[] convertedText = s.toCharArray();
	\end{verbatim}
	
	\begin{verbatim}
	

        for (int i=0; i < convertedText.length; i++)
	\end{verbatim}
	
	\begin{verbatim}
	

            rep[repIndex++] = convertedText[i];
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private int getInt() {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (repIndex < rep.length)
	\end{verbatim}
	
	\begin{verbatim}
	

            return (int) rep[repIndex++];
	\end{verbatim}
	
	\begin{verbatim}
	

        else
	\end{verbatim}
	
	\begin{verbatim}
	

            return -1;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private String getString() {
	\end{verbatim}
	
	\begin{verbatim}
	

        int paramLength = getInt();
	\end{verbatim}
	
	\begin{verbatim}
	

        int paramType = getInt();
	\end{verbatim}
	
	\begin{verbatim}
	

        sb.setLength(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        for (int i=0; i < paramLength; i++) {
	\end{verbatim}
	
	\begin{verbatim}
	

            if (repIndex < rep.length)
	\end{verbatim}
	
	\begin{verbatim}
	

              sb.append(rep[repIndex++]);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        return sb.toString();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    private int computeStorageSize() {
	\end{verbatim}
	
	\begin{verbatim}
	

        int totalSize = HEADER_SIZE;
	\end{verbatim}
	
	\begin{verbatim}
	

        Enumeration e = parameters.keys();
	\end{verbatim}
	
	\begin{verbatim}
	

        while (e.hasMoreElements()) {
	\end{verbatim}
	
	\begin{verbatim}
	

            String key = (String) e.nextElement();
	\end{verbatim}
	
	\begin{verbatim}
	

            totalSize += (2 + key.length());
	\end{verbatim}
	
	\begin{verbatim}
	

            String value = (String) parameters.get(key);
	\end{verbatim}
	
	\begin{verbatim}
	

            totalSize += (2 + value.length());
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        return totalSize;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void pack() {
	\end{verbatim}
	
	\begin{verbatim}
	

        int totalStorage = computeStorageSize();
	\end{verbatim}
	
	\begin{verbatim}
	

        rep = new char[totalStorage];
	\end{verbatim}
	
	\begin{verbatim}
	

        length = totalStorage - HEADER_SIZE;
	\end{verbatim}
	
	\begin{verbatim}
	

        repIndex = 0;
	\end{verbatim}
	
	\begin{verbatim}
	

        putInt(type);
	\end{verbatim}
	
	\begin{verbatim}
	

        putInt(tag);
	\end{verbatim}
	
	\begin{verbatim}
	

        putInt(length);
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        Enumeration e = parameters.keys();
	\end{verbatim}
	
	\begin{verbatim}
	

        while (e.hasMoreElements()) {
	\end{verbatim}
	
	\begin{verbatim}
	

            String key = (String) e.nextElement();
	\end{verbatim}
	
	\begin{verbatim}
	

            String value = (String) parameters.get(key);
	\end{verbatim}
	
	\begin{verbatim}
	

            putParameter(key,value);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void unpack() {
	\end{verbatim}
	
	\begin{verbatim}
	

        /* need to clear out the hashtable first */
	\end{verbatim}
	
	\begin{verbatim}
	

        parameters.clear();
	\end{verbatim}
	
	\begin{verbatim}
	

        repIndex = 0;
	\end{verbatim}
	
	\begin{verbatim}
	

        type = getInt();
	\end{verbatim}
	
	\begin{verbatim}
	

        tag = getInt();
	\end{verbatim}
	
	\begin{verbatim}
	

        length = getInt();
	\end{verbatim}
	
	\begin{verbatim}
	

        while (repIndex < rep.length) {
	\end{verbatim}
	
	\begin{verbatim}
	

            String key = getString();
	\end{verbatim}
	
	\begin{verbatim}
	

            String value = getString();
	\end{verbatim}
	
	\begin{verbatim}
	

            parameters.put(key,value);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public String toString() {
	\end{verbatim}
	
	\begin{verbatim}
	

        return “Message: type = “ 
	\end{verbatim}
	
	\begin{verbatim}
	

          + type 
	\end{verbatim}
	
	\begin{verbatim}
	

          + “ param = “
	\end{verbatim}
	
	\begin{verbatim}
	

          + parameters;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String args[]) {
	\end{verbatim}
	
	\begin{verbatim}
	

        Message m = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“v0”,”1.5”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“v1”,”2.0”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“person”,”Luiz”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.pack();
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        Message m2 = new Message(m.getCharArray());
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“v0 = “ + m2.getParam(“v0”));
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“v1 = “ + m2.getParam(“v1”));
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“person = “ + m2.getParam(“person”));
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-12107}
So what happens when a
\texttt{Message}
object is packed? Consider the following code, which has been excised from the
\texttt{main()}
method of the code just presented (this is a test case that you can run standalone to get an understanding of what’s going on):
\par

	\begin{verbatim}
	

        Message m = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“v0”,”1.5”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“v1”,”2.0”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“person”,”luiz”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.pack();
	\end{verbatim}
	
% Label
\label{pgfId-12398}
This code creates a
\texttt{Message}
instance
\texttt{m}
and sets three parameters with the
\texttt{setParam()}
method call. Then, the message is packed. When the message is packed, it is translated into a representation (character array) that is suitable for network transmission. (See the
\texttt{rep}
variable discussion from before).
\ref{id(29352)}[MISSING HREF]
shows the contents of the representation after packing:
\par

	%\begin{tabular}
	
% Label
\label{pgfId-12534}

% Label
\label{29352}
The packed representation of the preceding
\textbf{\texttt{Message}}
Messageinstance
% Label
\label{pgfId-12540}
Position
% Label
\label{pgfId-12542}
Content
% Label
\label{pgfId-12544}
Description and Comments
% Label
\label{pgfId-12546}

\texttt{rep+0}

% Label
\label{pgfId-12548}

\texttt{0}

% Label
\label{pgfId-12550}
The
\texttt{type}
field
% Label
\label{pgfId-12552}

\texttt{rep+1}

% Label
\label{pgfId-12554}

\texttt{0}

% Label
\label{pgfId-12556}
The
\texttt{tag}
field
% Label
\label{pgfId-12558}

\texttt{rep+2}

% Label
\label{pgfId-12560}

\texttt{N}

% Label
\label{pgfId-12562}
The
\texttt{length}
field
% Label
\label{pgfId-12564}

\texttt{rep+3}

% Label
\label{pgfId-12566}

\texttt{2}

% Label
\label{pgfId-12568}

% Label
\label{pgfId-12570}

\texttt{rep+4}

% Label
\label{pgfId-12572}

\texttt{T\underscore{}STRING}

% Label
\label{pgfId-12574}

\texttt{T\underscore{}STRING}
is an integer constant to flag as a
\texttt{String.}

% Label
\label{pgfId-12576}

\texttt{rep+5}

% Label
\label{pgfId-12578}

\texttt{‘v’}

% Label
\label{pgfId-12580}

% Label
\label{pgfId-12582}

\texttt{rep+6}

% Label
\label{pgfId-12584}

\texttt{‘0’}

% Label
\label{pgfId-12586}

% Label
\label{pgfId-12588}

\texttt{rep+7}

% Label
\label{pgfId-12590}

\texttt{3}

% Label
\label{pgfId-12592}

% Label
\label{pgfId-12594}

\texttt{rep+8}

% Label
\label{pgfId-12596}

\texttt{T\underscore{}STRING}

% Label
\label{pgfId-12598}
This version encodes everything as a
\texttt{String.}

% Label
\label{pgfId-12674}
Note that a float value may encode differently than
\texttt{typed}
.
% Label
\label{pgfId-12600}

\texttt{rep+9}

% Label
\label{pgfId-12602}

\texttt{‘1’}

% Label
\label{pgfId-12604}

% Label
\label{pgfId-12606}

\texttt{rep+10}

% Label
\label{pgfId-12608}

\texttt{‘.’}

% Label
\label{pgfId-12610}

% Label
\label{pgfId-12612}

\texttt{rep+11}

% Label
\label{pgfId-12614}

\texttt{‘5’}

% Label
\label{pgfId-12616}

% Label
\label{pgfId-12618}

\texttt{rep+12}

% Label
\label{pgfId-12620}

% Label
\label{pgfId-12622}
This will encode the parameter
\texttt{“v1”}
and
\texttt{”2.0”}

% Label
\label{pgfId-12624}

\texttt{rep+21}

% Label
\label{pgfId-12626}

% Label
\label{pgfId-12628}
This will encode the parameter
\texttt{“person”}
and
\texttt{”Luiz”}

	%\end{tabular}
	
% Label
\label{pgfId-12915}

\texttt{MessageServer}
and
\texttt{Deliverable}

\par

% Label
\label{pgfId-12916}
At the center of SMA is the
\texttt{MessageServer}
class.
\texttt{MessageServer}
is designed to be a generic container-style class for building your own services. It extends the
\texttt{Thread}
class and is intended to run as a server. If you can ignore a few details for the moment and focus attention on the
\texttt{run()}
method, it should be clear that the
\texttt{MessageServer}
class is in one respect not much different that the
\texttt{ThreadedDateTimeServer}
class discussed earlier. Consider the server loop (found in the
\texttt{run()}
method):
\par

	\begin{verbatim}
	

        while (true) {
	\end{verbatim}
	
	\begin{verbatim}
	

            try {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=callListener.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                MessageServerDispatcher csd;
	\end{verbatim}
	
	\begin{verbatim}
	

                csd = new MessageServerDispatcher(this, s);
	\end{verbatim}
	
	\begin{verbatim}
	

                csd.setDaemon(false);
	\end{verbatim}
	
	\begin{verbatim}
	

                csd.start();
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“Exception “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

                e.printStackTrace();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
% Label
\label{pgfId-12920}
A connection is accepted as always. A separate class,
\texttt{MessageServerDispatcher}
, is used to construct an instance that will actually handle the incoming connection. This technique was shown earlier in
\ref{id(32267)}[MISSING HREF]
. The code for the
\texttt{MessageServerDispatcher}
is shown in
\ref{id(89813)}[MISSING HREF]
. We will return to a discussion of this code shortly.
\par

% Label
\label{pgfId-12956}
Let us consider a few other aspects of the design of class
\texttt{MessageServer}
. Recalling the original figure showing the architecture of SMA, we see that objects that are interested in providing a service are called deliverables. Any class can provide service simply by implementing the
\texttt{Deliverable}
interface, which provides a single method:
\par

	\begin{verbatim}
	

        interface Deliverable {
	\end{verbatim}
	
	\begin{verbatim}
	

          Message send(Message m);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
% Label
\label{pgfId-12957}
This interface represents a contract of sorts. It says that a
\texttt{Deliverable}
object must provide a method
\texttt{send()}
that accepts an incoming
\texttt{Message m}
and returns a reply
\texttt{Message}
instance. Interfaces, by their very nature, are somewhat abstract, since they provide a mechanism for avoiding implementation details. After we have finished introducing all of the classes of SMA, there will be a concrete example that ties all of the principles together.
\par

% Label
\label{pgfId-12975}
The
\texttt{MessageServer}
class contains two important methods that pertain to deliverables:
\par

\begin{itemize}

\item{public void subscribe(int messageType, Deliverable d) : This method allows a given Deliverable d to subscribe to a particular type of message. Recall that every message has a type, which is set via the setType() method provided in class Message .}

% Label
\label{pgfId-12983}

\item{public Deliverable getSubscriber(int messageType) : This method returns the deliverable that is subscribed to a particular type of message. If there is no subscriber, null is returned.}

% Label
\label{pgfId-12984}

\end{itemize}

% Label
\label{pgfId-12985}
The concept of subscription is a very powerful concept for building protocols. In real protocols, the complexity is in writing the handler code for different message types. SMA gives the protocol designer the capability of building a protocol incrementally by ensuring that each type of message has a particular (and hopefully unique!) response. There is one aspect of subscription that needs to be clarified, however. Subscription is limited to one subscriber per message type. This is done to ensure clean semantics. To understand this, consider that a deliverable must reply to a message that is sent to it. If multiple deliverables are subscribers, there would be multiple replies. Which one is returned to the
\texttt{MessageClient}
? It’s possible to merge messages (we even provide a method for this capability); however, it can lead to confusion on the client side.
\par

% Label
\label{pgfId-12982}
But now we digress. Let us consider the details of the
\texttt{MessageServerDispatcher}
code, shown in
\ref{id(89813)}[MISSING HREF]
.
\par
MessageServer
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class MessageServer extends Thread {
	\end{verbatim}
	
	\begin{verbatim}
	

    private ServerSocket callListener;
	\end{verbatim}
	
	\begin{verbatim}
	

    private Hashtable subscribers;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static final boolean logging = true;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void log(String s) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (!logging) return;
	\end{verbatim}
	
	\begin{verbatim}
	

        System.err.println(“MessageServer: “ + s);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public MessageServer(int port) throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        log(“Simple Messaging Architecture (SMA) version 1.0”);
	\end{verbatim}
	
	\begin{verbatim}
	

        log(“Copyright (c) 2000, George K. Thiruvathukal”);
	\end{verbatim}
	
	\begin{verbatim}
	

        callListener = new ServerSocket(port);
	\end{verbatim}
	
	\begin{verbatim}
	

        subscribers = new Hashtable();
	\end{verbatim}
	
	\begin{verbatim}
	

        log(“Created MessageServer instance fully!”);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void subscribe(int messageType, Deliverable d) {
	\end{verbatim}
	
	\begin{verbatim}
	

        subscribers.put(messageType + ““, d);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Deliverable getSubscriber(int messageType) {
	\end{verbatim}
	
	\begin{verbatim}
	

        return (Deliverable) subscribers.get(messageType + ““);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void run() {
	\end{verbatim}
	
	\begin{verbatim}
	

        log(“MessageServer thread started. run() dispatched.”);
	\end{verbatim}
	
	\begin{verbatim}
	

        while (true) {
	\end{verbatim}
	
	\begin{verbatim}
	

            try {
	\end{verbatim}
	
	\begin{verbatim}
	

                Socket s=callListener.accept();
	\end{verbatim}
	
	\begin{verbatim}
	

                MessageServerDispatcher csd;
	\end{verbatim}
	
	\begin{verbatim}
	

                csd = new MessageServerDispatcher(this, s);
	\end{verbatim}
	
	\begin{verbatim}
	

                csd.setDaemon(false);
	\end{verbatim}
	
	\begin{verbatim}
	

                csd.start();
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“Exception “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

                e.printStackTrace();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-11510}
The
\texttt{MessageServerDispatcher}
class is responsible for handling an incoming message (from the
\texttt{MessageServer}
we just discussed). It is important to note that there is a parenting relationship between the
\texttt{MessageServer}
class and the
\texttt{MessageServerDispatcher}
class. (We exploit this relationship to determine from the
\texttt{MessageServer}
the subscriber for a particular type of message. This is why a
\texttt{MessageServer}
reference is maintained in each instance of
\texttt{MessageServerDispatcher}
that is created.
\par

% Label
\label{pgfId-12997}
The
\texttt{run()}
method (again) is where all of the action is for class
\texttt{MessageServerDispatcher}
. Let us focus on the loop in this method, which continuously accepts communications from a remote
\texttt{MessageClient}
and sends responses. This loop is excised and shown with annotations:
\par

	\begin{verbatim}
	

           while (true) {
	\end{verbatim}
	
% Label
\label{pgfId-13033}

\texttt{Message}
provides a factory method,
\texttt{getMessage()}
, to read one
\texttt{Message}
at a time from an underlying stream.
\texttt{in}
refers to input from the socket.
\par

	\begin{verbatim}
	

                Message m = Message.getMessage(in);
	\end{verbatim}
	
	\begin{verbatim}
	

                Message result = null;
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“Received Message “ + m + “.”);
	\end{verbatim}
	
% Label
\label{pgfId-13039}
If a message is found with the
\texttt{“\dollar{}disconnect”}
parameter (all variables beginning with “\dollar{}” are reserved by SMA), the client has gracefully decided to end the session.
\par

	\begin{verbatim}
	

                if (m.getParam(“$disconnect”) != null) {
	\end{verbatim}
	
	\begin{verbatim}
	

                    log(“$disconnect found in Message ” + m);
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.err.println(“-> Disconnect”);
	\end{verbatim}
	
	\begin{verbatim}
	

                    Message ack = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

                    ack.pack();
	\end{verbatim}
	
	\begin{verbatim}
	

                    ack.putMessage(out);
	\end{verbatim}
	
	\begin{verbatim}
	

                    socket.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                    return;
	\end{verbatim}
	
	\begin{verbatim}
	

                }
	\end{verbatim}
	
	\begin{verbatim}
	

                Deliverable d;
	\end{verbatim}
	
% Label
\label{pgfId-13040}
Find the subscriber that is interested in the type of message just received:
\par

	\begin{verbatim}
	

                d = callServer.getSubscriber(m.getType());
	\end{verbatim}
	
% Label
\label{pgfId-13041}
If there is a subscriber, deliver the message
\texttt{m}
and capture the reply in
\texttt{result}
; otherwise, there is no subscriber interested in this message. It is not a fatal error; however, we need to send an empty reply message back to ensure the client receives a reply:
\par

	\begin{verbatim}
	

                if (d != null) 
	\end{verbatim}
	
	\begin{verbatim}
	

                    result = d.send(m);
	\end{verbatim}
	
	\begin{verbatim}
	

                else {
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.err.println(“-> No subscribers found.”)
	\end{verbatim}
	
	\begin{verbatim}
	

                    result = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

                }
	\end{verbatim}
	
% Label
\label{pgfId-13046}
The
\texttt{pack()}
method (as discussed earlier) is called to arrange the message as an array of characters for transmission via the underlying output stream. Once the message is packed,
\texttt{putMessage()}
can be used to send it to the client:
\par

	\begin{verbatim}
	

                result.pack();
	\end{verbatim}
	
	\begin{verbatim}
	

                result.putMessage(out);
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
% Label
\label{pgfId-13054}
And that’s all there is to it.
\par
MessageServerDispatcher
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class MessageServerDispatcher extends Thread {
	\end{verbatim}
	
	\begin{verbatim}
	

    MessageServer callServer;
	\end{verbatim}
	
	\begin{verbatim}
	

    Socket socket;
	\end{verbatim}
	
	\begin{verbatim}
	

    InputStreamReader in;
	\end{verbatim}
	
	\begin{verbatim}
	

    OutputStreamWriter out;
	\end{verbatim}
	
	\begin{verbatim}
	

    public static final boolean logging = true;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    
	\end{verbatim}
	
	\begin{verbatim}
	

    public MessageServerDispatcher(MessageServer ms, Socket s)
	\end{verbatim}
	
	\begin{verbatim}
	

        throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        callServer = ms;
	\end{verbatim}
	
	\begin{verbatim}
	

        socket = s;
	\end{verbatim}
	
	\begin{verbatim}
	

        in = new InputStreamReader(socket.getInputStream());
	\end{verbatim}
	
	\begin{verbatim}
	

        out = new OutputStreamWriter(socket.getOutputStream());
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void log(String s) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (!logging) return;
	\end{verbatim}
	
	\begin{verbatim}
	

        System.err.println(“MessageServerDispatcher: “ + s);
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void run() {
	\end{verbatim}
	
	\begin{verbatim}
	

        log(“Beginning of dispatch run() method.”);
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            while (true) {
	\end{verbatim}
	
	\begin{verbatim}
	

                Message m = Message.getMessage(in);
	\end{verbatim}
	
	\begin{verbatim}
	

                Message result = null;
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“Received Message “ + m + “.”);
	\end{verbatim}
	
	\begin{verbatim}
	

                if (m.getParam(“$disconnect”) != null) {
	\end{verbatim}
	
	\begin{verbatim}
	

                    log(“$disconnect found in Message ” + m);
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.err.println(“-> Disconnect”);
	\end{verbatim}
	
	\begin{verbatim}
	

                    Message ack = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

                    ack.pack();
	\end{verbatim}
	
	\begin{verbatim}
	

                    ack.putMessage(out);
	\end{verbatim}
	
	\begin{verbatim}
	

                    socket.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                    return;
	\end{verbatim}
	
	\begin{verbatim}
	

                }
	\end{verbatim}
	
	\begin{verbatim}
	

                Deliverable d;
	\end{verbatim}
	
	\begin{verbatim}
	

                d = callServer.getSubscriber(m.getType());
	\end{verbatim}
	
	\begin{verbatim}
	

                if (d != null) 
	\end{verbatim}
	
	\begin{verbatim}
	

                    result = d.send(m);
	\end{verbatim}
	
	\begin{verbatim}
	

                else {
	\end{verbatim}
	
	\begin{verbatim}
	

                    System.err.println(“-> No subscribers found.”)
	\end{verbatim}
	
	\begin{verbatim}
	

                    result = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

                }
	\end{verbatim}
	
	\begin{verbatim}
	

                result.pack();
	\end{verbatim}
	
	\begin{verbatim}
	

                result.putMessage(out);
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (EOFException e1) {
	\end{verbatim}
	
	\begin{verbatim}
	

            try {
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“End of file exception.” + e1);
	\end{verbatim}
	
	\begin{verbatim}
	

                out.close();
	\end{verbatim}
	
	\begin{verbatim}
	

                socket.close();
	\end{verbatim}
	
	\begin{verbatim}
	

            } catch (Exception e2) {
	\end{verbatim}
	
	\begin{verbatim}
	

                log(“Unable to free open resources “ + e2);
	\end{verbatim}
	
	\begin{verbatim}
	

                e2.printStackTrace();
	\end{verbatim}
	
	\begin{verbatim}
	

            }
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch (Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            log(“Unknown exception “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

            e.printStackTrace();
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-13073}
The
\texttt{MessageClient}
object is used to establish a connection to a
\texttt{MessageServer}
object. The code for
\texttt{MessageClient}
is shown in
\ref{id(19156)}[MISSING HREF]
. To connect to a
\texttt{MessageServer}
object, the host and port must be specified in the constructor. Attempting to connect to anything other than a
\texttt{MessageServer}
object is likely to result in errors.
\par

% Label
\label{pgfId-13077}
The key method of interest in the
\texttt{MessageClient}
class is the
\texttt{call()}
method. Much like making a telephone call, the idea is that the
\texttt{MessageClient}
object can send a message to a
\texttt{MessageServer}
object. This method basically puts the message on the wire (using the
\texttt{putMessage()}
method from the
\texttt{Message}
class). Then, the factory method
\texttt{getMessage()}
is used to read the reply (another
\texttt{Message}
instance) off the wire. Again, note that the client and server only think in terms of
\texttt{Message}
instances. (Recall our earlier discussion about how the entire Internet was built on top of message formats that are defined as arrays of character data.)
\par

% Label
\label{pgfId-13078}
The other method of interest is the
\texttt{disconnect()}
method. When a
\texttt{MessageClient}
object no longer needs to interact with a remote
\texttt{MessageServer}
object, it is only polite to disconnect and give the server an opportunity to free up resources elegantly. Disconnection is handled by allocating a message and setting a reserved parameter named
\texttt{“\dollar{}disconnect”}
. When any message is seen by the server that contains this parameter, the session is ended.
\par

% Label
\label{pgfId-13084}
This completes the tour of all of the classes that comprise SMA. We conclude by showing how SMA can be used to reimplement the working date-and-time example.
\par
MesaageClient
	\begin{verbatim}
	

import java.io.*;
	\end{verbatim}
	
	\begin{verbatim}
	

import java.net.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class MessageClient extends Thread {
	\end{verbatim}
	
	\begin{verbatim}
	

    Socket socket;
	\end{verbatim}
	
	\begin{verbatim}
	

    OutputStreamWriter out;
	\end{verbatim}
	
	\begin{verbatim}
	

    InputStreamReader in;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public MessageClient(String host, int port)
	\end{verbatim}
	
	\begin{verbatim}
	

      throws IOException {
	\end{verbatim}
	
	\begin{verbatim}
	

        socket = new Socket(host, port);
	\end{verbatim}
	
	\begin{verbatim}
	

        out = new OutputStreamWriter(socket.getOutputStream());
	\end{verbatim}
	
	\begin{verbatim}
	

        in = new InputStreamReader(socket.getInputStream());    
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Message call(Message message) {
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            message.putMessage(out);
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.err.println(“MessageClient (call): “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

            return null;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            Message m = Message.getMessage(in);
	\end{verbatim}
	
	\begin{verbatim}
	

            m.unpack();
	\end{verbatim}
	
	\begin{verbatim}
	

            return m;
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.err.println(“MessageClient (reply): “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

            return new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public void disconnect() {
	\end{verbatim}
	
	\begin{verbatim}
	

        Message m = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setType(0);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“$disconnect”,”$disconnect”); 
	\end{verbatim}
	
	\begin{verbatim}
	

        call(m);
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            socket.close();
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.err.println(“MessageClient (disconnect): “+e);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
\subsubsection{DateService and DateClient SMA Style}

% Label
\label{pgfId-11652}

% Label
\label{pgfId-13085}

\ref{id(18316)}[MISSING HREF]
shows the implementation of the
\texttt{DateService}
class. This class shows the ability of SMA to help you build a network service without needing to know the details of socket programming and streams. You simply think in terms of getting a message and doing something with its parameters.
\par

% Label
\label{pgfId-13093}
SMA is somewhat different than programming with sockets. If you consider the earlier implementations of the date-and-time service (and its variants), as soon as the client opened a connection to the server, the server basically just writes the date to its output socket. The client immediately reads from its input socket until there is no more data. Then, the session is ended. SMA imposes
\emph{line discipline}
on the application. A message must be sent by the client to initiate a response on the part of the server. The server sends a reply that must be read by the client. Then, the client can send another message. This request-reply scenario is almost identical to remote procedure call semantics; however, the intent of SMA is not to be an RPC system, but instead is a set of building blocks for RPC.
\par

% Label
\label{pgfId-13094}
The
\texttt{DateService}
class implements the
\texttt{Deliverable}
interface. This means that it must provide a
\texttt{send()}
method that accepts a message and returns a reply. The incoming message
\texttt{m}
is actually ignored in the
\texttt{send()}
method, since the
\texttt{DateService}
object does not expect any parameters from the client. The message is modified by setting the
\texttt{date}
parameter with the
\texttt{String}
representation of today’s date and then returned. The act of returning a message from the
\texttt{send()}
method is the first step toward getting a result to the client. (The rest of the steps are handled in the
\texttt{MessageServerDispatcher}
code, which was already discussed.)
\par

% Label
\label{pgfId-13095}
To actually get a server running, it is necessary at some point to create a
\texttt{MessageServer}
instance and subscribe at least one instance of the
\texttt{DateService}
to it. It is also important to create a message type. In the
\texttt{DateService}
class, a number of constants have been defined:
\par

% Label
\label{pgfId-13096}

\textbf{\texttt{DATE\underscore{}SERVICE\underscore{}MESSAGE}}
DATE\underscore{}SERVICE\underscore{}MESSAGE: This represents a constant that will be used to represent the message type for communication with the
\texttt{DateService}
. The value is set to 100, but could in fact be any number, as long as
\texttt{DateClient}
and
\texttt{DateService}
agree on it. In
\texttt{DateClient}
, we have taken care to ensure that this constant is used as the message type.
\par

% Label
\label{pgfId-13097}

\textbf{\texttt{DATE\underscore{}SERVICE\underscore{}PORT}}
DATE\underscore{}SERVICE\underscore{}PORT: This represents the TCP/IP port that will be bound when creating the
\texttt{SocketServer}
(in the
\texttt{MessageServer}
class). Again, the
\texttt{DateService}
and
\texttt{DateClient}
objects must agree on this value.
\par

% Label
\label{pgfId-13101}
In the
\texttt{main()}
method, the
\texttt{DateService}
instance is created as well as a
\texttt{MessageServer}
instance. The following line of code shows how the
\texttt{DateService}
instance becomes formally known to the
\texttt{MessageServer}
:
\par

	\begin{verbatim}
	

        ms.subscribe(DATE_SERVICE_MESSAGE, ds);
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	DateService
	\begin{verbatim}
	

import java.util.*;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

public class DateService implements Deliverable {
	\end{verbatim}
	
	\begin{verbatim}
	

    public static final int DATE_SERVICE_MESSAGE = 100;
	\end{verbatim}
	
	\begin{verbatim}
	

    public static final int DATE_SERVICE_PORT = 1999;
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public Message send(Message m) {
	\end{verbatim}
	
	\begin{verbatim}
	

        Date today = new Date();
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“date”, today.toString());
	\end{verbatim}
	
	\begin{verbatim}
	

        return m;
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String args[]) {
	\end{verbatim}
	
	\begin{verbatim}
	

        DateService ds = new DateService(); 
	\end{verbatim}
	
	\begin{verbatim}
	

        MessageServer ms;
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            ms = new MessageServer(DATE_SERVICE_PORT);
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.err.println(“Could not start service “ + e);
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        Thread msThread = new Thread(ms);
	\end{verbatim}
	
	\begin{verbatim}
	

        ms.subscribe(DATE_SERVICE_MESSAGE, ds);
	\end{verbatim}
	
	\begin{verbatim}
	

        msThread.start();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
	\begin{verbatim}
	

}
	\end{verbatim}
	
% Label
\label{pgfId-13110}
The
\texttt{DateClient}
class in fact is just a driver and only provides a
\texttt{main()}
method. The real work happens where you see
\texttt{Message}

\texttt{m}
being instantiated. This message represents the
\texttt{request}
message that is being sent to the remote
\texttt{DateService}
. The
\texttt{setType()}
method is used to establish a type that corresponds to the value of the
\texttt{DateService}
, which is obtained from the
\texttt{DateService}
class, which defined a public static final variable
\texttt{DATE\underscore{}SERVICE\underscore{}MESSAGE}
. (Java makes this very convenient!) Just for show, we set a parameter named
\texttt{person}
to
\texttt{george}
and make the call. (This parameter, of course, will be ignored, since the
\texttt{DateService}
is just waiting for a message with the right type field and does not care about the parameters at all.) After the call is made,
\texttt{date}
is obtained by calling
\texttt{getParam()}
on the reply message, the value of which is subsequently printed.
\par

% Label
\label{pgfId-13115}
To show that SMA recovers gracefully from human error, a second message is also sent by this client. This message has a hard-coded type of 75 (not equal to the type expected by
\texttt{DateService}
). This message results in an empty message as a reply. If you have not disabled logging on the server side, you’ll notice that SMA provides detailed log messages to indicate that a message was received that “has no subscriber.”
\par
DateClient
	\begin{verbatim}
	

public class DateClient {
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

    public static void main(String[] args) {
	\end{verbatim}
	
	\begin{verbatim}
	

        if (args.length < 2) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.out.println(“Usage: DateClient host port”);
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	

        String host = args[0];
	\end{verbatim}
	
	\begin{verbatim}
	

        int port;
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            port = Integer.parseInt(args[1]);
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            port = DateService.DATE_SERVICE_PORT;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        MessageClient conn;
	\end{verbatim}
	
	\begin{verbatim}
	

        try {
	\end{verbatim}
	
	\begin{verbatim}
	

            conn = new MessageClient(host,port);
	\end{verbatim}
	
	\begin{verbatim}
	

        } catch(Exception e) {
	\end{verbatim}
	
	\begin{verbatim}
	

            System.err.println(e);
	\end{verbatim}
	
	\begin{verbatim}
	

            return;
	\end{verbatim}
	
	\begin{verbatim}
	

        }
	\end{verbatim}
	
	\begin{verbatim}
	


	\end{verbatim}
	
	\begin{verbatim}
	

        Message m = new Message();
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setType(DateService.DATE_SERVICE_MESSAGE);
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setParam(“person”,”george”);
	\end{verbatim}
	
	\begin{verbatim}
	

        m = conn.call(m);
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“Date “ + m.getParam(“date”));
	\end{verbatim}
	
	\begin{verbatim}
	

        m.setType(75);
	\end{verbatim}
	
	\begin{verbatim}
	

        m = conn.call(m);
	\end{verbatim}
	
	\begin{verbatim}
	

        System.out.println(“Bad reply “ + m);
	\end{verbatim}
	
	\begin{verbatim}
	

        conn.disconnect();
	\end{verbatim}
	
	\begin{verbatim}
	

    }
	\end{verbatim}
	
\section{Chapter Wrap-Up}

% Label
\label{pgfId-11792}

% Label
\label{22526}

% Label
\label{pgfId-14572}

% Label
\label{35275}
This chapter has provided an introduction to computer networking principles with the intention of providing a sufficiently self-contained introduction and saving you from having to consult other textbooks to understand the advanced material in the remaining chapter (Coordination), wherein it is shown how to build a sophisticated process and thread coordination framework. As well, we have provided a glimpse into how network services are implemented. The emphasis on simplicity (as in the streams chapter) is intentional, since it is assumed that you will fully understand the basics of streams and networking before attempting to read the very last chapter.
\par

% Label
\label{pgfId-14573}
SMA itself is being evolved to provide a very lightweight alternative to distributed object systems, such as RMI and CORBA, for building Internet services. There is good reason to believe such a (simplified) messaging framework may prove to be useful. At the time of writing, there is a flurry of activity to build new remote procedure calling (RPC) systems based on XML. One such system is called SOAP (Simple Object Access Protocol), which is an XML/RPC framework. XML is fundamentally a text based format, and so is SMA (although there is nothing to stop it from supporting binary data as well). The question then becomes one of overhead. XML is not a lightweight framework for structuring data. The data must be processed with an appropriate parser. Furthermore, while XML itself is fairly straightforward to learn (as is HTML), working with the parsers requires advanced programming knowledge, even when using the simple parsers. The ideas of SMA could actually be used to strike a balance between simplicity and flexibility. SMA “fields” could simply be XML data, when advanced structure is truly needed.
\par

% Label
\label{pgfId-14574}
There is a revised version of the SMA class library available from the book web site. This version supports more data types, binary data, and also has a number of fixes to address bugs that we have encountered using the Reader and Writer classes in Java. The revised version is based on Java’s data streams, which are based on byte streams and seem to work more reliably than the character streams.
\par

\section{Exercises}

% Label
\label{pgfId-13147}

% Label
\label{71115}

\begin{enumerate}

\item{In the box entitled “Using Telnet to Contact sendmail: The Unix Mail Delivery Service” the telnet client was used to connect to SMTP and compose a message. Find out what your SMTP server is at your institution, and use it to compose a message to yourself. Does it work?}

\item{Use telnet to connect to a site (preferably at your own institution) and interact with the World Wide Web server. You will more than likely need to specify the port numbered 80. Document the various commands that you can execute and what they do.}

\item{The PortScan example suggests that there are a number of “unknown services” listening on a number of ports. Is it necessarily the case that the service is unknown? Or is this a limitation of the program? Explain.}

\item{SMA as presented could also be extended to make use of DataInputStream and DataOutputStream . Explain why this would be better than packing an array structure and then writing to (or reading from) the underlying stream. Write a new version of SMA that makes use of DataInputStream and DataOutputStream to read and write Message instances. (You can also download the reworked version from the Java Web site.)}

\item{Use the SMA classes to implement a basic AuthenticationService class. This service will accept messages with username and password parameters and maintain a list of sessions. The authentication will be performed against a password file, which you can assume is an association between username and a plaintext password. The reply message should indicate whether or not the authentication could be performed. Upon successful login, a session identifier should be returned to the user. Time and interest permitting, extend this service to support the notion of an expiration period (a period after which a session will be destroyed).}

\item{Use SMA to extend the ideas of the previous question to create a general-purpose messaging system. After a user logs in, he or she can send messages to other users, retrieve incoming messages, etc. This type of service presents the possibility of a “denial of service” attack, since a user’s incoming message list could grow without bound. How would you prevent such attacks from occurring? (Hint: You will need to keep some parameters with the user information!)}

\item{In the RunQueueDateTimeServer example, we showed how to use the RunQueue class to service incoming network requests, thus alleviating the overhead of creating threads every time a connection is accepted on the ServerSocket object. Extend the SMA classes to make use of the same idea.}

\end{enumerate}

% Footnotes Skipped
